开发者

Javascript to match substring and strip everything after it

I need to match a substring X within string Y and nee开发者_运维问答d to match X then strip everything after it in Y.


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:

text1.indexOf(text2)

This returns the character position of the first instance of text2, in text 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!


If you're looking to match just X in Y and return only X, I'd suggest using match.

var x = "treasure";
var y = "There's treasure somewhere in here.";
var results = y.match(new RegExp(x)); // -> ["treasure"]

results will either be an empty array or contain the first occurrence of x.

If you want everything in y up to and including the first occurrence of x, just modify the regular expression a little.

var results2 = y.match(new RegExp(".*" + x)); // -> ["There's treasure"]


You can use substring and indexOf:

Y.substring(0, Y.indexOf(X) + X.length))

DEMO

Of course you should test beforehand whether X is in Y.


var index = y.indexOf(x);
y = index >= 0 ? y.substring(0, y.indexOf(x) + x.length) : y;


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜