Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to have value in string represented by %s and then replaced with a value

Tags:

javascript

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.

like image 427
jbx Avatar asked Jul 23 '10 13:07

jbx


People also ask

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

How would you convert a value to a string in JavaScript?

Values can be explicitly converted to strings by calling either String() or n. toString() . With the String() function, let's convert a Boolean value to a string by passing the value true into the parameters for String() . When we do this, the string literal "true" will be returned.

How do you replace a certain part of a string JavaScript?

replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.


2 Answers

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);
like image 128
Guffa Avatar answered Oct 04 '22 19:10

Guffa


'Modern' ES6 solution: use template literals. Note the backticks!

var email = '[email protected]';
var error_message = `An account already exists with the email: ${email}`;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

like image 41
MichielB Avatar answered Oct 04 '22 18:10

MichielB