iqueqiorio iqueqiorio - 1 month ago 6x
Javascript Question

Javascript Split on random number in string

I have a string that will look like one of these this


I want to split this string to get TEST and the Name after the "_", what regular expression can use to split it at
"/" + any number + "_"



Use match, and capturing groups:

var james = "TEST/4_James";
matches = james.match(/(.*)\/.*_(.*)/);

console.log(matches[1]); // TEST
console.log(matches[2]); // James

// In order of appearance
(.*)  //matches any character except newline and captures it
\/    //matches a forward slash
.*_   //matches any character except newline followed by an underscore
(.*)  //matches any character except newline (what's left) and captures it

Someone mentioned this: I use this as well and it's an awesome resource if you're learning regular expressions because it not only allows you to write and test them, but it's educational in the way it explains each piece of the regular expression and what it does.

Also it's a good idea to be a little more explicit in your expressions than .* if you can. For instance if you know that it's going to be numbers or characters, or a particular string then use a more explicit pattern. I just used this because I wasn't really sure what 'TEST' might contain in an actual scenario.