You can do this with the String.split
function, which splits a string into an array using a separator/token:
var token = 'begin';
var str="beginThetest";
var parts = str.split(token);
alert(parts[0]); //'Thetest'
If you don’t fully understand String.split
:
The parts
array only contains one element (parts[0]
) because there are no characters before the only occurrence of the token ('begin'
) in your string.
A lengthier example should make this clear:
var token = 'begin';
var str="THIS_TESTbeginTHAT_TESTbeginLAST_TEST";
var parts = str.split(token);
alert(parts[0]); //'THIS_TEST'
alert(parts[1]); //'THAT_TEST'
alert(parts[2]); //'LAST_TEST'
But if 'begin'
is always your token, what’s the point? You don’t need to split
, you can just do something like:
var str="beginThetest";
var token = 'begin';
var index = token.length;
var the_rest = str.substr(index);
alert(the_rest); //'Thetest'
And of course you can put that into an array if you’d like.