javascript Javascript匹配子字符串并删除它之后的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4690617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript to match substring and strip everything after it
提问by van
I need to match a substring X within string Y and need to match X then strip everything after it in Y.
我需要匹配字符串 Y 中的子字符串 X 并且需要匹配 X 然后在 Y 中删除它之后的所有内容。
回答by Tom Gullen
Code
代码
var text1 = "abcdefgh";
var text2 = "cde";
alert(text1.substring(0, text1.indexOf(text2)));
alert(text1.substring(0, text1.indexOf(text2) + text2.length));
First alert doesn't include search text, second one does.
第一个警报不包含搜索文本,第二个包含。
Explanation
解释
I'll explain the second line of the code.
我将解释代码的第二行。
text1.substring(0, text1.indexOf(text2) + text2.length))
text1.substring(startIndex, endIndex)
This piece of code takes every character from startIndex to endIndex, 0 being the first character. So In our code, we search from 0 (the start) and end on:
这段代码采用从 startIndex 到 endIndex 的每个字符,0 是第一个字符。所以在我们的代码中,我们从 0(开始)开始搜索并结束:
text1.indexOf(text2)
This returns the character position of the first instance of text2, in text 1.
这将返回 text2 的第一个实例在文本 1 中的字符位置。
text2.length
This returns the length of text 2, so if we want to include this in our returned value, we add this to the length of the returned index, giving us the returned result!
这将返回文本 2 的长度,因此如果我们想将其包含在我们的返回值中,我们将其添加到返回索引的长度中,从而得到返回的结果!
回答by Andrew Moore
If you're looking to match just X in Y and return only X, I'd suggest using match.
如果您只想匹配 Y 中的 X 并仅返回 X,我建议使用match.
var x = "treasure";
var y = "There's treasure somewhere in here.";
var results = y.match(new RegExp(x)); // -> ["treasure"]
resultswill either be an empty array or contain the first occurrence of x.
results将是一个空数组或包含第一次出现的x.
If you want everything in yup to and including the first occurrence of x, just modify the regular expression a little.
如果您想要y包含第一次出现的所有内容x,只需稍微修改正则表达式即可。
var results2 = y.match(new RegExp(".*" + x)); // -> ["There's treasure"]
回答by Felix Kling
回答by wombleton
var index = y.indexOf(x);
y = index >= 0 ? y.substring(0, y.indexOf(x) + x.length) : y;
回答by Poonam Bhatt
var X = 'S';
var Y = 'TEST';
if(Y.indexOf(X) != -1){
var pos = parseInt(Y.indexOf(X)) + parseInt(X.length);
var str = Y.substring(0, pos);
Y = str;
}
document.write(Y);

