Javascript to match the substring and strip everything after it

I need to match the substring X inside the string Y and need to combine X, and then pull everything after it to Y.

+5
source share
5 answers

the code

var text1 = "abcdefgh";
var text2 = "cde";

alert(text1.substring(0, text1.indexOf(text2)));
alert(text1.substring(0, text1.indexOf(text2) + text2.length));

The first warning does not include search text, the second -.

Explanation

I will explain the second line of 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 is the first character. So, in our code we find from 0 (beginning) and end:

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 return value, we add it to the length of the returned index, giving us the returned result!

+11

substring indexOf:

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

DEMO

, , X Y.

+4

X Y X, match.

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

results , x.

y x , .

var results2 = y.match(new RegExp(".*" + x)); // -> ["There treasure"]
+3
var index = y.indexOf(x);
y = index >= 0 ? y.substring(0, y.indexOf(x) + x.length) : y;
0
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

All Articles