2

How can I use sprintf in jQuery?

I'm trying to add an id to a chunk of HTML that is returned from a script

So:

success: function(html){
    $('.data').html($.sprintf(html,'TEST'));
},

The HTML that is returned is a large chunk of HTML where i've added a %s for sprintf to do it's replacement.

Eg: '<div>Welcome to Blah</div><div>You userId is %s</div>'

Norman
  • 6,159
  • 23
  • 88
  • 141

1 Answers1

14

If it's really as simple as you've described, just use String#replace with a regular expression (so you can use the g flag to make the replacement happen throughout the string):

$('.data').html(html.replace(/%s/g, 'TEST'));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Your solution worked really well. Just for my knowledge, cant sprintf be used in jQuery the way it's done in PHP. EG: sprintf($string,$m) – Norman Feb 06 '14 at 07:24
  • 1
    @Norman: Well, `$.sprintf` *does not exist*, so no, you can't use it. But of course you can create your own `sprintf` implementation and then you can use it. – Felix Kling Feb 06 '14 at 07:32