tags:

views:

40

answers:

4

Hi,

I know this a really stupid question.

I've had a good few years experience with javascript but this one thing seems to have skipped my mind, my head has gone blank and I can't remember what it's called and how I would go about doing it.

Basically what I'm looking for is when you have a string variable such as:

var error_message = "An account already exists with the email: %s"

And you then pass a string somehow into this and it replaces the %s.

I probably sound really idiotic, but I'd really appreciate the help / reminding!

Thanks guys.

+2  A: 

You may take a look at this: http://www.webtoolkit.info/javascript-sprintf.html

Macmade
Thanks, I will definitely bookmark this for future reference. That's where I got confused, between PHP and Javascript, thinking that there was a built in function. For the current project simply using the replace function will suffice.
jbx
+2  A: 

You just use the replace method:

error_message = error_message.replace('%s', email);

This will only replace the first occurance, if you want to replace multiple occurances, you use a regular expression so that you can specify the global (g) flag:

error_message = error_message.replace(/%s/g, email);
Guffa
A: 

See below

var error_message = "An account already exists with the email: %s"

var myNewString = error_message.replace(" %s", newdata);

Example

<script type="text/javascript">
var visitorName = "Chuck";
var myOldString = "Hello username! I hope you enjoy your stay username.";
var myNewString = myOldString.replace("username", visitorName);

document.write("Old string =  " + myOldString); 
document.write("<br />New string = " + myNewString);

</script>

Output for above.

Old string = Hello username! I hope you enjoy your stay username.
New string = Hello Chuck! I hope you enjoy your stay username.

Amit
@mkoryak, he is not using a regex..
Gaby
A: 

There is nothing quite like C's printf() or PHP's sprintf() functionality built into JavaScript. There is the replace() method of the string object which can be used to replace one thing with another - which could be used in this particular case, but it's limited.

There are several implementations around that others have written which cover a subset of sprintf()'s behaviour.

w3d