Reputation: 89
I know to get a substring between 2 characters we can do something like myString.substring(myString.lastIndexOf("targetChar") + 1, myString.lastIndexOf("targetChar"));
But how would I get a substring if the two targetChar
are the same. For example, if I have something like const myString = "/theResultSubstring/somethingElse"
, how would I extract theResultSubstring
in this case?
Upvotes: 0
Views: 335
Reputation: 44087
Do indexOf
and lastIndexOf
if there are only two characters in your string:
const myString = "/theResultSubstring/somethingElse";
const subString = myString.substring(myString.indexOf("/") + 1, myString.lastIndexOf("/"));
console.log(subString);
Or split
it:
const myString = "/theResultSubstring/somethingElse";
const subString = myString.split("/")[1];
console.log(subString);
Upvotes: 1
Reputation: 41893
You could use String#match
instead with following regex and positive & negative lookaheads.
const myString = "/theResultSubstring/somethingElse";
const res = myString.match(/(?!\/)\w+(?=\/)/)[0];
console.log(res);
Upvotes: 1