0

in below code if i replace temp in $(this).text(temp); with "something" it works and change span text, but when i use a string.format it doesn't work.

jquery code:

  var x = $("span.resource");           
  x.each(function () {            
       if ($(this).attr('id') = "l1") {
           var temp = String.Format("{0}/{1}", variable1,variable2);
           $(this).text(temp);
       });
hamze
  • 7,061
  • 6
  • 34
  • 43
  • Where does `variable1` and `variable2` come from? – mekwall Jun 06 '11 at 09:09
  • You might find [this link](http://stackoverflow.com/questions/610406/javascript-printf-string-format) useful , also you might find much more efficient to find the element with the `id=l1` using `$('#l1')` – jaime Jun 06 '11 at 09:12
  • Also, if you take a look at [MDC](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String) there's no method named `Format` for the `String` object. Are you perhaps confusing languages? ;) – mekwall Jun 06 '11 at 09:14
  • @Marcus Ekwall variables define global – hamze Jun 06 '11 at 10:12

2 Answers2

1

If you look at MDC there's no method named Format for the String object. My guess is that you are confusing languages (JavaScript and C#), which is quite common for multi-language developers.

However, everything's not lost. You can easily recreate an equivalent method in JavaScript by adding to the prototype of the String object. Credits go to gpvos, Josh Stodola, infinity and Julian Jelfs who contributed to these solutions to a similar problem.

String.prototype.format = function(){
  var args = arguments;
  return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};

With a little tweaking it should work like this:

$("span.resource").each(function(){
    if (this.id == "l1") {
        var $this = $(this),
            newText = $this.text().format(var1, var2);
        $this.text(newText);
    }
});

Blair Mitchelmore have a similar implementation on his blog, but with some extra features and added functionality. You might want to check that out as well!

Community
  • 1
  • 1
mekwall
  • 28,614
  • 6
  • 75
  • 77
0

You had syntax errors, and String.Format doesn't exist in javascript. This works:

  $("span.resource").each(function () {             
       if ($(this).attr('id') == "l1") {
           var temp = variable1 + '/' + variable2;
           $(this).text(temp);
       }
  });
Ant
  • 3,877
  • 1
  • 15
  • 14