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

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


Please find an example below, thanks.

/**
 * @param  {String} template
 * @param  {String[]} values
 * @return {String}
 */
function sprintf(template, values) {
  return template.replace(/%s/g, function() {
    return values.shift();
  });
}

Example usage:

sprintf('The quick %s %s jumps over the lazy %s', [
  'brown',
  'fox',
  'dog'
]);

Would output:

"The quick brown fox jumps over the lazy dog"

Tags:

Javascript