Nitin Aggarwal
Nitin Aggarwal

Reputation: 215

how to get substrings javascript?

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

Answers (3)

Ali Mamedov
Ali Mamedov

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

gurvinder372
gurvinder372

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

choz
choz

Reputation: 17858

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}}

Upvotes: 1

Related Questions