Funky
Funky

Reputation: 13602

Javascript String Replace

I have a string that I would like to replace certain values with empty string. My string is:

"col1=,,,&col2=,&col3=,,&item5,item8,"

I am trying to replace ",,," with ""

I have tried the following and had no joy, does anyone have any ideas what the best way to achieve this is?

var string = "col1=,,,&col2=,&col3=,,&item5,item8,";
var NewCookie = "";

NewCookie = string.replace(",,", ",");
NewCookie = NewCookie.replace(',,,', ',');
NewCookie = NewCookie.replace(',,&', ',');

alert(NewCookie);

Thanks

Upvotes: 2

Views: 946

Answers (5)

MozenRath
MozenRath

Reputation: 10030

while(str.indexOf(",,")!=-1){
     str = str.replace(",,",",");
}

Upvotes: -1

Andrew D.
Andrew D.

Reputation: 8210

Try this:

var result = "col1=,,,&col2=,&col3=,,&item5,item8,".replace(/,+&?/g,',');

Result string is: "col1=,col2=,col3=,item5,item8,"

or

var result = "col1=,,,&col2=,&col3=,,&item5,item8,".replace(/=?,+&?/g,'=&');

Result string is: "col1=&col2=&col3=&item5=&item8=&"

or

var result = "col1=,,,&col2=,&col3=,,&item5,item8,".replace(/,+/g,',');

Result string is: "col1=,&col2=,&col3=,&item5,item8,"

Upvotes: 3

expertCode
expertCode

Reputation: 533

Try this function:

function RemoveConsecutiveCharacter(str, character){
    var newStr = "";

    $.each(str, function(index){
        if(str[index] != character || str[index-1] != character){
            newStr += str[index];
        }
    });

    return newStr;
}

See an example here: http://jsfiddle.net/expertCode/6naAB/

Upvotes: 1

Curtis
Curtis

Reputation: 103338

You are replacing ",," to "," which results in:

"col1=,,&col2=,&col3=,&item5,item8,"

Therefore, when you do:

NewCookie = NewCookie.replace(',,,', ',');

there are no longer any ",,,"

Try rearranging your replace functions:

NewCookie = string.replace(',,,', ',');
NewCookie = NewCookie.replace(",,", ",");
NewCookie = NewCookie.replace(',&', ',');

Upvotes: 0

Andy
Andy

Reputation: 30135

this works for me:

alert( ("col1=,,,&col2=,&col3=,,&item5,item8,").replace(',,,',',') );

edit: ah you set NewCookie to "" then you want to replace something in NewCookie (which is "") in example 2 and 3. you have to set var NewCookie = string; in your example.
or do

var NewCookie = string.replace(',,,',',');

Upvotes: 0

Related Questions