2017-08-02 49 views
-1

我在使用javascript替换函数时遇到问题。当搜索模式包含Javascript替换函数不工作? mark

"demo text?for test".replace(new RegExp("text?for", 'g'), "text for"); 

它的返回输出是“用于测试的演示文本?”。

我想,我错过了一些东西,但我不知道。

下面是我的功能我在应用程序中使用

var replaceAll = function (targetString, search, replacement) { 
      return targetString.replace(new RegExp(search, 'g'), replacement); 
     }; 

replaceAll("This is my favorite video https://www.youtube.com/watch?v=n3MPiLq0fKc", "video https://www.youtube.com/watch?v=n3MPiLq0fKc", "http://d-d.co/4eDED") 

输出是“这是我最喜欢的视频https://www.youtube.com/watch?v=n3MPiLq0fKc

+1

'?'在正则表达式中有特殊含义。你需要逃避那个角色。 – zzzzBov

回答

1

你的代码的工作,只要你提供的正则表达式作为封闭在/字符串并用特殊字符的正确转义,像这样:

var replaceAll = function(targetString, search, replacement) { 
 
    return targetString.replace(new RegExp(search, 'g'), replacement); 
 
}; 
 

 
console.log(replaceAll("This is my favorite video https://www.youtube.com/watch?v=n3MPiLq0fKc", /video https:\/\/www\.youtube\.com\/watch\?v=n3MPiLq0fKc/, "http://d-d.co/4eDED"))

+0

感谢您的回复。我们可以在替换之前通过任何javascript函数在文本中添加转义字符吗? –

+0

RegExp.escape = function(s){ return s.replace(/ [ - \/\\^$ * +?。()| [\] {}]/g,'\\ $ &'); }; –