I have the following string:
[27564][85938][457438][273][48232]
I want to replace all the [ with ''. I tried the following but it didn't work:
var str = '[27564][85938][457438][273][48232]'
var nChar = '[';
var re = new RegExp(nChar, 'g')
var visList = str.replace(re,'');
what am I doing wrong here?
Many thanks in advance.
A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the g flag, or use replaceAll() instead.
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
You need to escape the [
otherwise it is interpreted as the start of a character class:
var nChar = '\\[';
If nChar is a variable (and I assume it is otherwise there would be little point in using RegExp
instead of /.../g
) then you may find this question useful:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With