Below is my string :
api/Node-1/{Node-1}/Node-1-1/{Node-1-1}
Search Term : 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.
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 '-' . 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/
尝试使用全非表达式
console.log('api/Node-1/{Node-1}/Node-1-1/{Node-1-1}'.replace(new RegExp("Node-1[^-]","gi"),"Learning"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.