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?
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}}
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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.