Reputation: 215
I have a string like var str = 'Foo faa {{Question14}} {{Question23}}'
. Now I want to get the substrings {{Question14}}
and {{Question23}}
by doing some operation on str
. The digit part is variable in the str
's substrings. I need to replace these substrings with their respective ids. How can I do that?
Upvotes: 1
Views: 55
Reputation: 5256
You can do It by this way:
var
str = 'Foo faa {{Question14}} {{Question23}}',
arr = str.match(/{{Question[0-9]+}}/igm);
alert(arr[0]); // {{Question14}}
alert(arr[1]); // {{Question23}}
Replace matches with some IDs:
str.replace(/{{Question([0-9]+)}}/igm, "id=$1"); // "Foo faa id=14 id=23"
When the regular expression contains groups (denoted by parentheses), the matches of each group are available as $1 for the first group, $2 the second, and so on.
Upvotes: 1
Reputation: 68373
try this
var str = 'Foo faa {{Question14}} {{Question23}}';
var replacements = {
"{{Question14}}" : "Hello",
"{{Question23}}" : "Hi",
};
var output = str.replace(/{{\w+}}/g, function(match){ return replacements [match] });
console.log(output);
Upvotes: 0