2

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

2
  • &item5,item8 isn't a valid query string. Can you clarify what format you want? Commented Sep 9, 2011 at 10:08
  • You can show result what you want? Commented Sep 9, 2011 at 10:32

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

0

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(',,,',',');

Comments

0

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(',&', ',');

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.