[英]Find and replace exact word in long string
Below is my string : 下面是我的字符串:
api/Node-1/{Node-1}/Node-1-1/{Node-1-1}
Search Term : Node-1 搜索词: Node-1
Replace with : Learning 替换为:学习
Expected output : 预期产量:
api/Learning/{Learning}/Node-1-1/{Node-1-1}
Now here the problem is Node-1 is matching with other Node-1-1 also but I want exact word matching and replacement. 现在,这里的问题是节点1也与其他节点1-1匹配,但我想进行精确的单词匹配和替换。
I have tried lots of options but none of them is working for me. 我尝试了很多选择,但没有一个对我有用。
function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } function escapeRegExp(str) { return str.replace(/([.*+?^=!:${}()|\\[\\]\\/\\\\])/g, "\\\\$1"); } console.log(replaceAll('api/Node-1/{Node-1}/Node-1-1/{Node-1-1}','Node-1','Learning')); var replaceStr = 'Node-1'; console.log( 'api/Node-1/{Node-1}/Node-1-1/{Node-1-1}'.replace(new RegExp("\\\\b"+replaceStr+"\\\\b","gi"),"Learning")); console.log( 'api/Node-1/{Node-1}/Node-1-1/{Node-1-1}'.replace(/\\bNode-1\\b/g,'Learning'));
Update : This question is not duplicate as my first answer is taken from this reference only which is not working with my input case. 更新:此问题不是重复的,因为我的第一个答案仅来自此参考 ,而该参考不适用于我的输入情况。
Try this : 尝试这个 :
function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } function escapeRegExp(str) { return str + '(?![-])'; } console.log(replaceAll('api/Node-1/{Node-1}/Node-1-1/{Node-1-1}', 'Node-1', 'Learning'));
It searches every str
occurence not followed by '-' . 它搜索没有出现在'-'之后的每个
str
。 You can add other characters not to match if you want inside the character set. 如果需要在字符集中添加其他不匹配的字符。
Hope this one fixes your problem: 希望这能解决您的问题:
var a = "api/Node-1/{Node-1}/Node-1-1/{Node-1-1}";
var arr = a.split("/");
for (var i=0; i<arr.length; i++) {
var word = arr[i].replace(/[^a-zA-Z1-9- ]/g, "");
if (word=="Node-1"){
arr[i] = arr[i].replace("Node-1", "Learning");
}
}
newString = arr.join("/");
console.log(newString);
check fiddle: https://jsfiddle.net/z8v0xt98/ 检查小提琴: https : //jsfiddle.net/z8v0xt98/
尝试使用全非表达式
console.log('api/Node-1/{Node-1}/Node-1-1/{Node-1-1}'.replace(new RegExp("Node-1[^-]","gi"),"Learning"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.