3

I have below string.

const msg='this is the ${sentence} to end all ${sentence}'

I want to replace all occurances of ${sentence} by 'message'.

When I am doing

var newMsg = msg.replace('${sentence}', 'message')

It gives output-

this is the message to end all ${sentence}

But I want to replace all occurances of ${sentence}. So I tried

var newMsg = msg.replace(/${sentence}/g, 'message')

And what if I want to replace all occurance of dynamic String.

var str = JSON.stringify(JsonData).toString();                 
  for (let [key, value] of Object.entries(dummyData)) {    
       str = str.replace('${'+key+'}', value)
}

Here JsonData is the JSON file whoes values I want to replace with values from dummyData(which is an object) Please suggest how can I achieve this. Thanks in advance.

  • 2
    @sagivbg I'm not ok with the duplicate as in that case it can be done by changing the quotes with ` to make it a [`template litteral`](https://beta.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals). making it not a replacement problem but a quoting problem – jonatjano Aug 07 '19 at 12:24
  • @jonatjano that is if the js engine supports it. – epascarello Aug 07 '19 at 13:36
  • 1
    @epascarello bad habit of me to ignore IE but even [microsoft say you should not use it anymore](https://www.zdnet.com/article/microsoft-security-chief-ie-is-not-a-browser-so-stop-using-it-as-your-default/), also template literal is so largelly available that engine not supporting it already need babel and the like to do anything – jonatjano Aug 07 '19 at 13:47

2 Answers2

2

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If pattern is a string, only the first occurrence will be replaced.

You pattern is a plain string, not a regex pattern. So you should use regex pattern with global (g) flag.

const msg='this is the ${sentence} to end all ${sentence}'
var newMsg = msg.replace(/\${sentence}/g, 'message')
console.log(newMsg)

Update:

As per your comment if you need to build the regex pattern dynamically then you can use RegExp class to build the pattern. Your code might be the following way:

var str = JSON.stringify(JsonData).toString();

for (let [key, value] of Object.entries(dummyData)) {
    let pattern = new RegExp(`/${key}/g`);
    str = str.replace(pattern, value);
    console.log(str);
}
MH2K9
  • 11,951
  • 7
  • 32
  • 49
  • Thanks for help. But What if I want to replace all occurance of **dynamic String**. var str = JSON.stringify(JsonData).toString(); for (let [key, value] of Object.entries(dummyData)) { str = str.replace('${'+key+'}', value) } – JAYASHRI SHINDE Aug 07 '19 at 13:28
  • @JAYASHRISHINDE, please see the **update** section. – MH2K9 Aug 07 '19 at 15:42
2

A more general way with regex ,you can do like this

const msg='this is the ${sentence} to end all ${sentence}'
let str=msg.replace(/\${(.*?)\}/g,"message");
console.log(str)


// you might use template literals 
let sentence="message";
const msg2=`this is the ${sentence} to end all ${sentence}`

console.log(msg2)
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
  • 1
    template litteral is the answer here, regex is only what op proposed because he didn't know template litteral I think – jonatjano Aug 07 '19 at 13:32