0

I just want to replace the tags with its available value.

But in a string may have multiple of same tags.

So i need to fetch and replace,

Array Sample :

 var result = {
     '[name]':'user_name',
     '[age]':29
 };

String :

<p id="text">
Hi [name], I really want to thank you. 
You([name]), really done a great job.

user,
 [name]-[age]
</p>

Javascript :

  var text = document.getElementByID('text');
  text.replace(string, value); // this replacement only helps first hit.

Here, i use "[name]" for 3 times, i have replacement value.

But i cant use ".replace()" function, because it wont work on second tag (if same).

Is it Possible ?

Or Any other Solution to Solve this ?

Thanks in Advance.

Shankar Thiyagaraajan
  • 1,705
  • 4
  • 28
  • 46
  • `replace()` only replaces the first occurence. Use a RexExp instead. – Num Lock Dec 02 '16 at 10:22
  • yes it is possible to replace all tags. This similar to templates resolution in general. you can use any template engine like handlebar, underscore template. – sandyJoshi Dec 02 '16 at 10:22

4 Answers4

1

You can use a regex that captures your pattern and then use function that will fetch value from object.

var str = document.getElementById('text').innerHTML;
var result = {
  '[name]': 'user_name',
  '[age]': 29
};
var reg = /(?:^|\[)(.*?)(?:}|\])/g
str = str.replace(reg, function(s) {
  // if key exists in object, replace its value, do not replace anything
  return result[s] || s;
})

console.log(str)
<p id="text">
  Hi [name], I really want to thank you. You([name]), really done a great job. user, [name]-[age]. This is a [dummy] test case
</p>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

Generate regex from the string and replace with property value. where yo can use RegExp to generate the regex from the string.

var result = {
  '[name]': 'user_name',
  '[age]': 29
};

var text = document.getElementById('text').innerHTML;
res = text.replace(
  // generate regex
  new RegExp(
    // get all keys from object
    Object.keys(result)
    // iterate and escape symbols which have special meaning in regex
    .map(function(v) {
      return v.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
    })
    // join using pipe symbol and set global modifier
    // for replacing all occurenece
    .join('|'), 'g'),
  // use callback to replace with value in object
  function(m) {        
  // get value from object if exist or return the same if not found
    return result[m] || m;
  });

console.log(res);
<p id="text">
  Hi [name], I really want to thank you. You([name]), really done a great job. user, [name]-[age]
</p>

Refer : Converting user input string to regular expression

Other method references :

  1. Object.keys
  2. Array#map
  3. Array#join
  4. String#replace

UPDATE : If patterns are the same then use a simple pattern match regex and replace using a callback function.

var result = {
  '[name]': 'user_name',
  '[age]': 29
};

var text = document.getElementById('text').innerHTML;
res = text.replace(/\[\w+\]/g, function(m) {
  // get value from object if exist or return the same if not found
  return result[m] || m;
})

console.log(res);
<p id="text">
  Hi [name], I really want to thank you. You([name]), really done a great job. user, [name]-[age]
</p>
Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
-1

Or even more simply... This is an example for [name], you would add string and value as necessary.

var text = document.getElementById('text').textContent;
text.replace(/\[name\]/g, 'Hello');
curv
  • 3,796
  • 4
  • 33
  • 48
-2

To replace multiple times in JavaScript you can use RegExp replace.

var text = document.getElementByID('text');
var regex= new RegExp(string,'gmi'); // g: global, m: multiline, i: ignore case
text.replace(regex, value);
Ali Bahrami
  • 5,935
  • 3
  • 34
  • 53