Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Replace with js

Tags:

javascript

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.

like image 795
neojakey Avatar asked Nov 10 '11 20:11

neojakey


People also ask

How do you perform global replacement with JS regular expression?

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.

Is there a Replace All in JavaScript?

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.

What is replace () in JavaScript?

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.

What can I use instead of replaceAll in JavaScript?

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')


1 Answers

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:

  • Is there a RegExp.escape function in Javascript?
like image 127
Mark Byers Avatar answered Oct 03 '22 04:10

Mark Byers