Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  188] [ 4]  / answers: 1 / hits: 19882  / 14 Years ago, fri, january 14, 2011, 12:00:00

I need to match a substring X within string Y and need to match X then strip everything after it in Y.


More From » string

 Answers
225

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!


[#94223] Wednesday, January 12, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pierre

Total Points: 716
Total Questions: 128
Total Answers: 102

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
pierre questions
Fri, Nov 6, 20, 00:00, 4 Years ago
Fri, Sep 4, 20, 00:00, 4 Years ago
Thu, Jul 18, 19, 00:00, 5 Years ago
Sun, Dec 2, 18, 00:00, 6 Years ago
Fri, Oct 26, 18, 00:00, 6 Years ago
;