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?
Add a comment
|
3 Answers
This is when RegEx comes in handy.
var str = 'Foo faa {{Question14}} {{Question23}}'
var pattern = /(\{\{[a-zA-Z0-9]+\}\})/gi;
var matches = str.match(pattern);
console.log(matches[0]); //{{Question14}}
console.log(matches[1]); //{{Question23}}
1 Comment
Nitin Aggarwal
what is the purpose of /gi? Can you please explain?
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.