您好我们有以下文字
这是水果 $ apple $ ,第二个水果是 $ mango $ ,第三个水果是的 $ $香蕉
现在在JavaScript中,我们需要在 $ .. $ 之间找到文字,并在每次出现时随机替换我自己的文字
这是 $ five apples $ 的结果,第二个水果是 $ two芒果$ 和第三个水果是 $香蕉是黄色的
这样的事情,主要目标是找到 $$ 之间的所有字符串并替换为新文本。
任何人都可以帮助我简单的java脚本正则表达式或任何其他快速的方法。
答案 0 :(得分:2)
我认为你想要的是:
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);
答案 1 :(得分:1)
这样的事情应该有效:
https://jsfiddle.net/mewcg3zo/
var text = "This is fruit is $apple$ and second fruit is $mango$ and the third fruit is $banana$";
var matches = text.match(/\$(.*?)\$/g);
var newText = ['$five apples$', '$two mangoes$', '$bananas are yellow$'];
$.each(matches, function(index, match) {
text = text.replace(match, newText[index]);
});
alert(text);