user1989
user1989

Reputation: 217

Passing Query String in Javascript/Jquery

I want to use string.format and window.location in Javascript. I want to redirect my page to a specific url and want to pass query strings in it.

If, there is any other way then this, please suggest me else inform me where am I wrong in this code.

// This doesn't work
function ABC() {    
var v1 = String.format("Page1.aspx?id={0}&un={1}", Id, "name");
                window.location = v1;
}

// This works
function ABC() {    
    window.location = String.format("Page1.aspx?id=" + Id);
    }

Upvotes: 0

Views: 82

Answers (3)

Lumi Lu
Lumi Lu

Reputation: 3305

function ABC() {    
  window.location = "Page1.aspx?id=" + Id + "&un=name";
}

Upvotes: 1

Marco Bonelli
Marco Bonelli

Reputation: 69276

There's no such thing as String.format in JavaScript, you can either build your own function to format a string or use the normal syntax with the + operator.

Here's a solution:

// Build your own format function
function formatString(s) {
    for (var i=1; i < arguments.length; i++) {
        s.replace(new RegExp('\\{'+(i-1)+'\\}', 'g'), arguments[i]);
    }

    return s;
}

function ABC() {
    var queryString = formatString("Page1.aspx?id={0}&un={1}", Id, "name");
    window.location.assign(queryString);
}

// Or use the reular syntax:
function ABC() {
   window.location.assign("Page1.aspx?id="+ Id + "&un=name");
}

Upvotes: 1

Med.Amine.Touil
Med.Amine.Touil

Reputation: 1235

Try this way

window.location.assign('/Page1.aspx?id='+ Id + '&un='+'name');

Upvotes: 1

Related Questions