Replace multiple instances of text surrounded by specific characters in JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Let’s say the following is our string. Some text is surrounded by special character hash(#) −

var values = "My Name is #yourName# and I got #marks# in JavaScript subject";

We need to replace the special character with valid values. For this, use replace() along with shift().

Example

Following is the code −

var values = "My Name is #yourName# and I got #marks# in JavaScript subject";
const originalValue = ["David Miller", 97];
var result = values.replace(/#([^#]+)#/g, _ => originalValue.shift());
console.log(result);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo298.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo298.js
My Name is David Miller and I got 97 in JavaScript subject
raja
Updated on 09-Nov-2020 10:53:16

Advertisements