-1

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

3 Answers3

1

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');
VC.One
  • 13,314
  • 4
  • 23
  • 52
ldtcoop
  • 690
  • 4
  • 13
1

[] 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)
Code Maniac
  • 35,187
  • 4
  • 31
  • 54
1

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

enter image description here

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

Prathibha Chiranthana
  • 792
  • 1
  • 12
  • 27