简体   繁体   中英

How to replace a string with square brackets using javascript replace function?

I have a string [TEST][NO CHANGE][TEST][NOW][TEST] in which [TEST] should be replace with 'replaced', and the result should be replaced[NO CHANGE]replaced[NOW]replaced.

I have Tried the following ways, nothing worked. 1. str.replace(/'[TEST]'/g, 'replaced'); 2. str.replace(/[TEST]/g, 'replaced'); 3. str.replace('/[TEST]/g', 'replaced');

var str = "[TEST][NO CHANGE][TEST][NOW][TEST]";
var resultStr = str.replace(/'[TEST]'/g, 'replaced'); 

Actual String: [TEST][NO CHANGE][TEST][NOW][TEST] After Replacing: replaced[NO CHANGE]replaced[NOW]replaced

Your regular expression in replace is looking for the string '[TEST]' surrounded by those single quotes and is looking to match any of the characters in TEST because you didn't escape the brackets. Try this regular expression instead:

var resultStr = str.replace(/\[TEST\]/g, 'replaced');

[] has a special meaning in regex, which means character class , if you want to match [] you need to escape them

 var str = "[TEST][NO CHANGE][TEST][NOW][TEST]"; var resultStr = str.replace(/\\[TEST\\]/g, 'replaced'); console.log(resultStr) 

Try to update using Below snippet.

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};
var str = "[TEST][NO CHANGE][TEST][NOW][TEST]";
var result = str.replaceAll('\[TEST\]','replaced')
console.log(result);

replaced[NO CHANGE]replaced[NOW]replaced

在此处输入图片说明

Src : How to replace all occurrences of a string in JavaScript

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM