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.

1
  • Why are you using RegExp instead of /.../g? Could the value of nChar change? Commented Nov 10, 2011 at 20:45

3 Answers 3

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:

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.