javaScript text.replace只替换了我想要替换的一个单词

时间:2016-10-08 16:59:53

标签: javascript html css

所以我想知道为什么我的

    var newText = text.replace("like", "love");

接着是

    var newText = text.replace("pie", "tie food"); 

只用“领带食物”取代“馅饼”而不用“爱”代替“喜欢” 所以这就是我所拥有的:

    <textarea id="text3" type="text" name="paragraph_text" style="height:500px; width: 1315px" cols="50" rows="10"></textarea>
<script>
  function replace(){
    var text = document.getElementById("text3").value;
    var newText = text.replace("like", "love");
    var newText = text.replace("pie", "tie food");
    document.getElementById("text3").value = newText;
  }
</script>

正如我所说,它只用“领带食物”取代“馅饼”而不是用“爱”取代“喜欢”。

所以这就是文本框所说的内容:

    I like eating pie

点击“替换”按钮后,我想说出

    I love eating tie food

我该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以链接替换,因为String#replace会返回一个新字符串:

  

replace() 方法返回一个新字符串,其中一个或所有匹配的模式由替换替换。模式可以是字符串或RegExp,替换可以是字符串或要为每个匹配调用的函数。

var text = 'I like eating pie',
    newText = text.replace("like", "love").replace("pie", "tie food");

console.log(newText);

答案 1 :(得分:1)

这是一个通用的解决方案,其中map是替换的映射对象(每个键都将替换为值,可以简单地扩展)

var map = {pie: 'tie food', like: 'love'}     
var reg = new RegExp(Object.keys(map).join('|'), 'gi')

var text = 'I like eating pie'

var newText = text.replace(reg, function(matched) {
  return map[matched];
})