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);
}
Marco Bonelli
70.7k21 gold badges129 silver badges152 bronze badges
asked Mar 13, 2015 at 15:22
3 Answers 3
function ABC() {
window.location = "Page1.aspx?id=" + Id + "&un=name";
}
answered Mar 13, 2015 at 15:35
Comments
Try this way
window.location.assign('/Page1.aspx?id='+ Id + '&un='+'name');
answered Mar 13, 2015 at 15:27
Comments
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");
}
answered Mar 13, 2015 at 15:34
Comments
lang-js
String.Format
is a C# function, not javascript.