Javascript reg表达式由不在.replace()中工作的变量创建

Javascript reg表达式由不在.replace()中工作的变量创建,javascript,Javascript,我正在做一个编码挑战,希望我们创建一个函数,找到并替换句子中的一个单词。我这样定义reg表达式 //"before" is the parameter with the word to be replaced var regRep = '/'+before+'/gi'; //"str" is the sentence to search and prepAfter" is a variable with the replacement word. var newStr = str.replac

我正在做一个编码挑战,希望我们创建一个函数,找到并替换句子中的一个单词。我这样定义reg表达式

//"before" is the parameter with the word to be replaced
var regRep = '/'+before+'/gi';
//"str" is the sentence to search and prepAfter" is a variable with the replacement word.
var newStr = str.replace(regRep, prepAfter);
我就是这样用的

//"before" is the parameter with the word to be replaced
var regRep = '/'+before+'/gi';
//"str" is the sentence to search and prepAfter" is a variable with the replacement word.
var newStr = str.replace(regRep, prepAfter);
返回
newStr
时,我得到原始
str
,没有任何修改。我检查了一下,并
console.log()
编辑了我的每个变量和逻辑块,
replace()
方法是唯一不能正常工作的方法。这是整个函数

function myReplace(str, before, after) {
    var prepAfter = "";
    var caseCheck = before.charAt(0);
    var regRep = '/'+before+'/gi';

    if(caseCheck === caseCheck.toUpperCase()){
      var firstLetter = after.substr(0,1).toUpperCase();
      var wordLength = after.length -1;
      var remWord = after.substr(1,wordLength);

      prepAfter = firstLetter.concat(remWord);
    }
    else{ prepAfter = after; }

    var newStr = str.replace(regRep, prepAfter);

    return newStr;
}
我错过了什么

var regRep = new RegExp(before, 'gi');
如果将字符串传递给
replace()
(与您一样),它将查找实际的字符串

注意:如果
before
在您的情况下只是一个单词,您甚至可能不需要正则表达式,只需按原样将其传递给
replace()
。这取决于您是否需要在前后检查空格之类的内容

如果将字符串传递给
replace()
(与您一样),它将查找实际的字符串

注意:如果
before
在您的情况下只是一个单词,您甚至可能不需要正则表达式,只需按原样将其传递给
replace()
。这取决于你是否需要在前后检查空格。

是的,只是做
replace(before,preafter)
就行了。感谢您刚刚做了
更换(之前、之后)
工作。谢谢