unknown
unknown

Reputation: 385

Remove unwanted characters from a string

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!

Upvotes: 2

Views: 3956

Answers (2)

Vitim.us
Vitim.us

Reputation: 22128

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 "]"

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

Behold the power of regular expressions:

str = str.replace(/[\]\[]/g,'');

Upvotes: 10

Related Questions