1

Hi all I am framing a url with Query string in javascript as follows every thing works fine but a comm is coming in between the query string so can some one help me

<script type="text/javascript">
    function RedirectLocation() {
        var cntrl = "Q1;Q2";
        var str_array = cntrl.split(';');
        var cnt = str_array.length;
        if (cnt == 0) {
            location.href = '/callBack.aspx';
        }
        else {
            var arr = [];
            for (var i = 0; i < str_array.length; i++) {
                str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
                arr.push(str_array[i] + '=1');
                if (i != str_array.length - 1) {
                    arr.push('&');
                }
            }
            location.href = '/Sample.aspx?' + arr;
        }
    }
</script>

This is giving me the query string as follows Sample.aspx?Q1=1,&,Q2=1 I need this to be like `Sample.aspx?Q1=1&Q2=1

3 Answers 3

5

To remove the commas from a string you could simply do

s = s.replace(/,/g,'');

But in your specific case, what you want is not to add the commas. Change

location.href = '/Sample.aspx?' + arr;

to

location.href = '/Sample.aspx?' + arr.join('');

What happens is that adding an array to a string calls toString on that array and that function adds the commas :

""+["a","b"] gives "a,b"

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

Comments

4

Don't rely on the implicit string conversion (which concatenates the array elements with a comma as separator), explicitly .join the array elements with &:

var arr = [];
for (var i = 0; i < str_array.length; i++) {
    str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
    arr.push(str_array[i] + '=1');
}
location.href = '/Sample.aspx?' + arr.join('&');

Think about it like this: You have a set of name=value entries which you want to have separated by &.

1 Comment

+1 I didn't check your code (I trust you enough) but pushing the '&' in the array isn't the best solution.
0

You can use arr.join(glue) to concatenate Array elements with something inbetween. In your case glue would be an empty string arr.join("").

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.