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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3318621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:50:36  来源:igfitidea点击:

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

javascript

提问by jbx

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.

我已经有几年的 javascript 经验了,但是这件事似乎让我忘记了,我的脑袋一片空白,我不记得它叫什么以及我将如何去做。

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.

然后你以某种方式将一个字符串传递给它,它替换了 %s。

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

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

Thanks guys.

多谢你们。

采纳答案by Guffa

You just use the replacemethod:

您只需使用以下replace方法:

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:

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

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

回答by MichielB

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

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

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

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

回答by Jamie Mason

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"

回答by honyovk

I just wrote a new function to handle this:

我刚刚写了一个新函数来处理这个:

function sprint(str, o) {
    if (typeof str !== "string" || typeof o !== "object") {
        return;
    }
    var regex = /%s\(([a-zA-Z0-9_]{1,15})\)/g,
        i;
    if (regex.test(str)) {
        str = str.replace(regex, function (found, match) {
            return o[match];
        });
    } else {
        for (i in o) {
            str = str.replace(/%s/, o[i]);
        }
    }
    return str;
}

And a few tests:

还有一些测试:

// Ordered Array mode
var s0 = sprint("This is %s %s call, using an %s in order", ["a", "function", "array"]);

// Ordered|Unordered Obejct Literal mode
var s1 = sprint("This is a %s(sw) function, %s(ma)! You need to %s(ch) this out...", {
    ma: "mang",
    sw: "sweet", //This is purposely out of order
    ch: "check"
});

console.log(s0);
console.log(s1);

https://gist.github.com/mbjordan/5807011

https://gist.github.com/mbjordan/5807011

回答by Macmade

回答by MrWhite

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 replaceone thing with another - which could be used in this particular case, but it's limited.

没有什么比JavaScript 内置的Cprintf()或 PHP 的sprintf()功能更像的了。有replace()一种字符串对象的方法可用于一件事替换为另一件事 - 可以在这种特殊情况下使用,但它是有限的。

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

其他人编写了几个实现,它们涵盖了sprintf()的行为的一个子集。

回答by Ankit Kumar

You can write your own sprintffunction:

您可以编写自己的sprintf函数:

function sprintf(str, ...args) {
  return args.reduce((_str, val) => _str.replace(/%s|%v|%d|%f|%d/, val), str);
}
const s  = sprintf("An account already exists with the email: %s", "SOME_ERROR");
console.log(s); // "An account already exists with the email: SOME_ERROR"

// OR bind this function in String's prototype

String.prototype.sprintf = function (...args) {
  return args.reduce((_str, val) => _str.replace(/%s|%v|%d|%f/, val), this);
};

const str = "one %s, two %d, three %v".sprintf(1, 2, 3);
console.log(str) // "one: 1, two: 2, three: 3"

you can pass multiple %s or %v or %d

你可以通过多个 %s or %v or %d

const str2 = sprintf("one %s, two %d, three %v", 1, 2, 3)
console.log(str2); // "one: 1, two: 2, three: 3"

回答by Amit Soni

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.

旧字符串 = 你好用户名!我希望你喜欢你的用户名。
新字符串 = 你好查克!我希望你喜欢你的用户名。