2

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
  • 795,719
  • 175
  • 1,089
  • 1,143
unknown
  • 385
  • 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

10

Behold the power of regular expressions:

str = str.replace(/[\]\[]/g,'');
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • 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
  • 20,746
  • 15
  • 92
  • 109