0

I'm trying to find a clean way to extract a substring from between two other substrings.So far I can do it based on targeting a specific character, but not a string. E.g (this doesn't work)

 var element = "Firstconstantmystring_lastconstant";
 var mySubString = element.substring(
                            element.lastIndexOf("Firstconstant") + 1,
                            element.lastIndexOf("_lastconstant")
                        );

I'm trying to extract "mystring" from the full string. I know that "Firstconstant" and "_lastconstant" will always be the same. Grateful for any help.

0

3 Answers 3

3

You can use a regular expression.

var string = 'Firstconstantmystring_lastconstant'
console.log(string.match(/(?<=Firstconstant)[\s\S]*(?=_lastconstant)/))

This will return an array with the first element being the result you want if there is a match, or null if there is no match.

Resources:

Sign up to request clarification or add additional context in comments.

1 Comment

You should also mention about the performance between substring and regex!!!
1

You should take the length from the first:

var element = "Firstconstantmystring_lastconstant";
var mySubString = element.substring(
                            "Firstconstant".length,
                            element.lastIndexOf("_lastconstant")
                        );
console.log(mySubString);

Comments

1
function substringBetween(s, a, b) {
var p = s.indexOf(a) + a.length;
return s.substring(p, s.indexOf(b, p));
}

var element = "Firstconstantmystring_lastconstant;";
var mySubString = substringBetween(element,'Firstconstant','_lastconstant')

console.log({mySubString })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.