1

I want to remove the characters [ and ] inside a variable. How can I do this? My variable is something similar to this one:

var str = "[this][is][a][string]";

Any suggestion is very much appreciated!

Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
unknown
  • 375
  • 3
  • 6
  • 18
  • possible duplicate of [Remove characters from a string](http://stackoverflow.com/questions/4846978/remove-characters-from-a-string) – Felix Kling Nov 08 '11 at 18:19

2 Answers2

9

Behold the power of regular expressions:

str = str.replace(/[\]\[]/g,'');
Blazemonger
  • 86,267
  • 25
  • 136
  • 177
  • thank you for the quick reply! ^^.. i have an additional question though. how can i remove "[" and "]" + the string inside it except for the last string in my variable(which is "string").. im new to jQuery regular expression – unknown Nov 08 '11 at 18:35
  • @unknown I'm not clear on what you mean. I would suggest familiarizing yourself with regular expressions, or else just parse the string using `str.split()` to find what you want. – Blazemonger Nov 08 '11 at 18:37
0

the fastest way

function replaceAll(string, token, newtoken) {
    while (string.indexOf(token) != -1) {
        string = string.replace(token, newtoken);
    }
    return string;
}

All you need to do is this...

var str = "[this][is][a][string]";

srt=replaceAll(str,'[','');    //remove "["

str=replaceAll(str,']','');    //remove "]"
Vitim.us
  • 18,445
  • 15
  • 88
  • 102