views:

33

answers:

1

I try to remove some non-safe characters from a string but i believe i have a problem on my RegExp object.

What i try to do below is if there are chars whose encoded length is greater than 3 chars they should be replaced with a space.

So if encoded value is %3D which is = sign, it is ok to have in my string. But if it is an apostrophe %E2%80%99 it should be replaced with a space.

val = "Angelina’s";
valEnc = encodeURIComponent(val);

for(var i = 0; i < val.length; i++){
    var a = val.substr(i,1);
    if(encodeURIComponent(a).length > 3){
        console.log(a, encodeURIComponent(a));
        var re = new RegExp(encodeURIComponent(a),"ig");
        valEnc.replace(re," ");
    };
};

console.log(decodeURIComponent(valEnc));

This code works and logs me the unwanted chars but it can not replace them with spaces, what am i doing wrong? Thanks.

+2  A: 

You seem to be using regular expressions unnecessarily here. One way to do this is to build up the result string one character at a time:

val = "Angelina’s";
valEnc = "";

for(var i = 0; i < val.length; i++){
    var a = val.substr(i,1);
    var e = encodeURIComponent(a);
    if(e.length <= 3){
        valEnc += e;
    }
}

console.log(decodeURIComponent(valEnc));
Greg Hewgill
Absolutely right, i should better get some sleep and continue with a fresh brain. Thanks dude...
Sinan Y.