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.
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.
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.
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.
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);
'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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With