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

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



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
Updated on: 2020-11-09T10:53:16+05:30

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements