时间:2010-07-23 13:37:55

标签: javascript

8 个答案:

答案 0 :(得分:11)

答案 1 :(得分:9)

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

var email = 'somebody@example.com';
var error_message = `An account already exists with the email: ${email}`;

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

答案 2 :(得分:7)

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

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

使用示例:

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

输出:

"The quick brown fox jumps over the lazy dog"

答案 3 :(得分:2)

答案 4 :(得分:2)

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

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;
}

还有一些测试:

// 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

答案 5 :(得分:1)

答案 6 :(得分:0)

答案 7 :(得分:0)

您可以编写自己的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"

您可以传递多个%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"