Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  108] [ 5]  / answers: 1 / hits: 73770  / 13 Years ago, thu, july 28, 2011, 12:00:00

I'm trying this:



str = bla [bla];
str = str.replace(/\[\]/g,);
console.log(str);


And the replace doesn't work, what am I doing wrong?



UPDATE: I'm trying to remove any square brackets in the string,
what's weird is that if I do



replace(/[/g, '')
replace(/]/g, '')


it works, but

replace(/[]/g, '');
doesn't.


More From » regex

 Answers
2

It should be:



str = str.replace(/[.*?]/g,);


You don't need double backslashes () because it's not a string but a regex statement, if you build the regex from a string you do need the double backslashes ;).



It was also literally interpreting the 1 (which wasn't matching). Using .* says any value between the square brackets.



The new RegExp string build version would be:



str=str.replace(new RegExp(\[.*?\],g),);


UPDATE: To remove square brackets only:



str = str.replace(/[(.*?)]/g,$1);


Your above code isn't working, because it's trying to match [] (sequentially without anything allowed between). We can get around this by non-greedy group-matching ((.*?)) what's between the square brackets, and using a backreference ($1) for the replacement.



UPDATE 2: To remove multiple square brackets



str = str.replace(/[+(.*?)]+/g,$1);
// bla [bla] [[blaa]] -> bla bla blaa
// bla [bla] [[[blaa] -> bla bla blaa


Note this doesn't match open/close quantities, simply removes all sequential opens and closes. Also if the sequential brackets have separators (spaces etc) it won't match.


[#90943] Wednesday, July 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
benitoh

Total Points: 150
Total Questions: 113
Total Answers: 104

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
benitoh questions
Sun, Mar 21, 21, 00:00, 3 Years ago
Mon, May 13, 19, 00:00, 5 Years ago
;