1

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?

3 Answers 3

1

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}}
Sign up to request clarification or add additional context in comments.

1 Comment

what is the purpose of /gi? Can you please explain?
1

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.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.