Reputation: 1297
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.
Upvotes: 0
Views: 180
Reputation: 126
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 })
Upvotes: 1
Reputation: 68933
You should take the length from the first:
var element = "Firstconstantmystring_lastconstant";
var mySubString = element.substring(
"Firstconstant".length,
element.lastIndexOf("_lastconstant")
);
console.log(mySubString);
Upvotes: 1
Reputation: 2834
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:
String.prototype.match
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchUpvotes: 3