Javascript:未定义字符串的格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25227119/
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-28 04:12:01  来源:igfitidea点击:

Javascript: string's format is not defined

javascript

提问by navyad

I have following snippet of javascript code:

我有以下javascript代码片段:

var someValue = 100;
var anotherValue = 555;
alert('someValue is {0} and anotherValue is {1}'.format(someValue, anotherValue));

getting following error:

收到以下错误:

Uncaught TypeError: undefined is not a function

what am i missing, here ?

我错过了什么,在这里?

回答by KooiInc

String.formatis not a native Stringextension. It's pretty easy to extend it yourself:

String.format不是本机String扩展。自己扩展它很容易:

if (!String.prototype.format) {
  String.prototype.format = function(...args) {
    return this.replace(/(\{\d+\})/g, function(a) {
      return args[+(a.substr(1, a.length - 2)) || 0];
    });
  };
}
// usage
console.log("{0} world".format("hello"));
.as-console-wrapper { top: 0; max-height: 100% !important; }

[Update 2020]

[ 2020 年更新]

It's not that fashionable anymore to extend native objects. Although I don't oppose it (if used carefully) a format-function can do exactly the same, or you can use es20xx template literals(see MDN).

扩展原生对象不再那么流行了。虽然我不反对它(如果小心使用format- 函数可以完全相同,或者您可以使用 es20xx template literals(请参阅MDN)。

// no native String extension
const someValue = 100;
const otherValue = 555;
const format = (str2Format, ...args) => 
  str2Format.replace(/(\{\d+\})/g, a => args[+(a.substr(1, a.length - 2)) || 0] );
console.log(format("someValue = {0}, otherValue = {1}", someValue, otherValue));

// template literal
console.log(`someValue = ${someValue}, otherValue = ${otherValue}`);
.as-console-wrapper { top: 0; max-height: 100% !important; }

回答by Ortal Blumenfeld Lagziel

String.format = function() {
            var s = arguments[0];
            for (var i = 0; i < arguments.length - 1; i += 1) {
                var reg = new RegExp('\{' + i + '\}', 'gm');
                s = s.replace(reg, arguments[i + 1]);
            }
            return s;
        };


var strTempleate = String.format('hello {0}', 'Ortal');