如何在JavaScript中创建replaceAll函数?

时间:2014-06-17 01:53:28

标签: javascript jquery string function

目前我正在尝试在JavaScript中创建一个带有三个参数的函数;
1.模板字符串
2.要替换的词 3.要替换的单词

这是我尝试的内容:

function replaceAll(templateString, wordToReplace, replaceWith)
{
    var regex = new RegExp("/" + wordToReplace + "/","g");
    return templateString.replace(regex, replaceWith);
}

console.log(replaceAll('My name is {{MyName}}', '{{MyName}}', 'Ahmed'));

但是它还在给我templateString。没有更换。
这就是我的回复:My name is {{MyName}}

2 个答案:

答案 0 :(得分:0)

这是一种不使用正则表达式的方法。

var replaceAll = function(tmpString, wordToReplace, wordToReplaceWith){
  return tmpString.split(wordToReplace).join(wordToReplaceWith);
}

replaceAll(str, '{{MyName}}', 'Ahmed'); //    "My name is Ahmed"

答案 1 :(得分:0)

您的代码是正确的,除非您在使用RegExp类时不需要开头和结尾'/':

function replaceAll(templateString, wordToReplace, replaceWith)
{
    var regex = new RegExp(wordToReplace,"g");
    return replacedString = templateString.replace(regex, replaceWith);
}

console.log(replaceAll('My name is {{MyName}}', '{{MyName}}', 'Ahmed'));