Kiran Kiran - 7 months ago 85
Javascript Question

Replace every occurrence string between two characters in a large text using regular expression in Javascript

Hi We have the following text

This is fruit is $apple$ and second fruit is $mango$ and the third fruit is $banana$

Now in JavaScript we need to find text between $..$ and replace with my own text on every occurrence randomly

This is fruit is $five apples$ and second fruit is $two mangoes$ and the third fruit is $bananas are yellow$

some thing like this, the main objective is find all strings between $$ and replace with new text.

can any one help me simple java script regular expression or any other method which is fast.

Answer

I think what you want is this:

var text = "This is fruit is $apple$ and second fruit is $the mangoes$ and the third fruit is $ price \\$ of banana$";

var replace = ['hello', 'these', 'are', 'some', 'random', 'strings'];

var matches = text.match(/\$(?:[^\$\\]|\\.)*\$/g);

matches.forEach(function(match) {
  random = '$' + replace[Math.floor(Math.random() * replace.length)] + '$';
  text = text.replace(match, random)
});

alert(text);
Comments