Javascript:如何在%s表示的字符串中使用值,然后用值替换

jbx*_*jbx 11 javascript

我知道这是一个非常愚蠢的问题.

我有几年的javascript经验,但这一件事似乎已经跳过了我的脑海,我的头已经空白,我不记得它叫什么,以及我将如何去做.

基本上我正在寻找的是当你有一个字符串变量,如:

var error_message = "An account already exists with the email: %s"
Run Code Online (Sandbox Code Playgroud)

然后你以某种方式将字符串传递给它并替换%s.

我可能听起来很愚蠢,但我真的很感激帮助/提醒!

多谢你们.

Guf*_*ffa 11

你只需使用该replace方法:

error_message = error_message.replace('%s', email);
Run Code Online (Sandbox Code Playgroud)

这只会替换第一次出现,如果要替换多次出现,可以使用正则表达式,以便指定global(g)标志:

error_message = error_message.replace(/%s/g, email);
Run Code Online (Sandbox Code Playgroud)


Mic*_*elB 9

'现代'ES6解决方案:使用模板文字.注意反引号!

var email = 'somebody@example.com';
var error_message = `An account already exists with the email: ${email}`;
Run Code Online (Sandbox Code Playgroud)

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


Jam*_*son 7

请在下面找一个例子,谢谢.

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

用法示例:

sprintf('The quick %s %s jumps over the lazy %s', [
  'brown',
  'fox',
  'dog'
]);
Run Code Online (Sandbox Code Playgroud)

输出:

"The quick brown fox jumps over the lazy dog"
Run Code Online (Sandbox Code Playgroud)