jacky
jacky

Reputation: 524

javascript get substring between two sets of characters

I have the following string:

var myString = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>';

how can i get with the least code the someExtraStuff.fileExt section?

should i do indexOf {{appName}} and then until the next "/> ?

Upvotes: 4

Views: 166

Answers (2)

Nishant Dixit
Nishant Dixit

Reputation: 5522

You can do this with three methods

// 1 option For single match

var regex = /\{\{appName\}\}([^"]+)/;
var myString = '<p class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/>';
console.log(myString.match(regex)[1]);

// 2 option For multiple matches

var regex = /\{\{appName\}\}([^"]+)/g;
var myString = '<p class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/>';
var temp;
var resultArray = [];
while ((temp = regex.exec(myString)) != null) {
    resultArray.push(temp[1]);
}
console.log(resultArray);

// 3 option For indexOf

var firstIndex= myString.indexOf("{{appName}}");
var lastIndex =firstIndex+ myString.substring(firstIndex).indexOf('"/>')
var finalString = myString.substring(firstIndex,lastIndex).replace("{{appName}}","");
console.log(finalString);

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386520

You could search for the pattern {{appName}} and take all characters who are not quotes. Then take the second element of the match.

var string = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>',
    substring = (string.match(/\{\{appName\}\}([^"]+)/) || [])[1]

console.log(substring);

Upvotes: 2

Related Questions