1

Possible Duplicate:
JavaScript equivalent to printf/string.format

I am creating code like this:

var ds = "ds=" + encodeURIComponent($('#DataSource').val());
var ex = "ex=" + encodeURIComponent($('#EID').val());
var to = "to=" + encodeURIComponent($('#TID').val());
var st = "st=" + encodeURIComponent($('#SID').val());
window.location.href = '/person?' + ds + "&" + ex + "&" + to + "&" + st;

Is there some way in Javascript that I could use formatting to make the code look a bit cleaner? Also do I need to encode each element or can I just encode the variable abc?

Community
  • 1
  • 1
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • Built-in.. NO. But you can find an implementation at http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/4673436#4673436 – Gabriele Petrioli Oct 31 '11 at 10:18

5 Answers5

1

There's not a lot you can do, really. You could alias the encodeURIComponent method and use an array with join() if you're looking for something a little neater:

var e = encodeURIComponent, 
    arr = [
        "ds=" + e($('#DataSource').val()),
        "ex=" + e($('#EID').val()),
        "to=" + e($('#TID').val()),
        "st=" + e($('#SID').val())
    ];

window.location.href = '/person?' + arr.join("&");
Andy E
  • 338,112
  • 86
  • 474
  • 445
0

Use <form> and put your input tags in them and you can call $('formContainer').serialize();

Its better to use name-value pairs(query strings), while sending data to URI. provide names as id to all of the input tags that you wish to capture. You will get something like:

/person/DataSource=ds&EID=ex&TID=to&SID=st

-HTH

Amit Gupta
  • 577
  • 4
  • 14
0

Why don't you just write:

window.location.href = encodeURIComponent('/person?' + 
    $('#DataSource').val() + "&" 
    + $('#EID').val() + "&" + $('#TID').val() + "&"
    + $('#SID').val());
itsjavi
  • 2,574
  • 2
  • 21
  • 24
0

Take a look at sprintf()

Also this can help: JavaScript equivalent to printf/string.format

Community
  • 1
  • 1
Pedram Behroozi
  • 2,447
  • 2
  • 27
  • 48
0
var str = "/person?ds=%x&ex=%x&to=%x&st=%x";

var tokens = [
  $("#DataSource").val(),
  $("#EID").val(),
  $("#TID").val(),
  $("#SID").val()
];

tokens.forEach(function (token) {
  str = str.replace("%x", encodeURIComponent(token));
});

location.href = str;

This will absolutely fall over if you have %x in your token string.

If you want a more generic solution try underscore.string

Raynos
  • 166,823
  • 56
  • 351
  • 396