Javascript - 仅在完美匹配时替换

时间:2017-04-05 18:29:17

标签: javascript regex join replace

我目前正在研究javascript,我偶然发现了这个问题。有没有一种方法可以指定只有在完美匹配时才能替换单词?

PS:我认为' g'将解决问题,但它只在中途完成。



var text = "Isabella is moving to New York in March";
var words = ["is","in"];
var combine = new RegExp(words.join("|"),"g");

text = text.replace(combine,"REPLACE");
console.log(text);




4 个答案:

答案 0 :(得分:3)

你可以将连接的单词包装在一个组中(最好是非捕获的)然后用单词边界/\b(?:word1|word2|...|wordn)\b/g 包围groub,这样正则表达式将如下所示:

var combine = new RegExp("\\b(?:" + words.join("|") + ")\\b", "g");
//                       ^^^^^^^^^^^               ^^^^^^^^^

更改:

var text = "Isabella is moving to New York in March";
var words = ["is","in"];
var combine = new RegExp("\\b(?:" + words.join("|") + ")\\b","g");

text = text.replace(combine," REPLACE ");
console.log(text);

示例:



g




注意: var room_1_beds = 2; var room_2_beds = 2; var room_3_beds = 1; var give_num = prompt(); var x; switch(give_num){ case "1": x = room_1_beds; break; case "2": x = room_2_beds; break; case "3": x = room_3_beds; break; default: break; } switch(x){ case "1": console.log ("text"); break; case "2": console.log ("text"); break; default: break; } 修饰符表示全局(意味着不仅替换第一个匹配而且全部匹配)

答案 1 :(得分:2)

只在单词中添加空格:)



var text = "Isabella is moving to New York in March";
var words = [" is "," in "];
var combine = new RegExp(words.join("|"),"g");

text = text.replace(combine," REPLACE ");
console.log(text);




答案 2 :(得分:2)

通过完美匹配,我假设您的意思是仅匹配单词本身而不是可能包含您正在搜索的单词的字符的单词内部。您正在寻找RegExp的单词边界功能。试试这个修改后的代码请注意\b添加到结尾并开始。基本上,它充当一个锚点,表示仅在与模式匹配的整个单词的实例中匹配此RegEx。我还将这些单词放在一个捕获组中,因此单词边界适用于所有这些单词。

var text = "Isabella is moving to New York in March";
var words = ["is","in"];
var combine = new RegExp("\\b(" + words.join("|") + ")\\b","g");

text = text.replace(combine,"REPLACE");
console.log(text);

答案 3 :(得分:2)

不同的方法:将字符串解析为数组并使用此数组

var text = "Isabella is moving to New York in March";
    
var words = ['in', 'is'];
    
var result = text.split(' ').filter(el => {return !words.includes(el)}).join(' ');

console.log(result);