3

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>'

1

1 Answer 1

15

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')); 
Sign up to request clarification or add additional context in comments.

2 Comments

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: 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.