X_C95
X_C95

Reputation: 89

JS how to get the substring between two identical string character

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

Answers (2)

Jack Bashford
Jack Bashford

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

kind user
kind user

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

Related Questions