5

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.

neojakey
  • 1,633
  • 4
  • 24
  • 36

3 Answers3

7

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:

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1
var string = "[27564][85938][457438][273][48232]";
alert(string.replace(/\[/g, '')); //outputs 27564]85938]457438]273]48232]

I escaped the [ character and used a global flag to replace all instances of the character.

Jasper
  • 75,717
  • 14
  • 151
  • 146
0

I met this problem today. The requirement is replace all "c++" in user input string. Because "+" has meaning in Reg expression, string.replace fails. So I wrote a multi-replace function for js string. Hope this can help.

String.prototype.mreplace = function (o, n) {
    var off = 0;
    var start = 0;
    var ret = "";
    while(true){
        off = this.indexOf(o, start);
        if (off < 0)
        {
            ret += this.substring(start, this.length);
            break;
        }
        ret += this.substring(start, off) + n;
        start = off + o.length;
    }
    return ret;
}

Example: "ababc".mreplace("a", "a--"); // returns "a--ba--bc"

jarjar
  • 1