jQuery中类似于String.format的函数是什么?

205

我正在尝试将一些JavaScript代码从MicrosoftAjax迁移到JQuery。 我使用MicrosoftAjax中流行的.net方法的JavaScript等效方法,例如String.format(),String.startsWith()等。 在jQuery中是否有与它们相当的方法?


2
请参考以下链接,了解JavaScript中类似于printf的字符串格式化函数:https://dev59.com/YXRB5IYBdhLWcg3weXOX - John
22个回答

0

使用函数式编程:

// 'Hello, {0} {1}'.format('FirstName', 'LastName') -> 'Hello, FirstName LastName'
String.prototype.format = function () {
  const initialValue = this.toString();
  const numberOfArguments = arguments.length || 0;
  const formattedValue = [...Array(numberOfArguments)].reduce((accumulator, currentValue, index) => {
    const replacementPattern = new RegExp('\\{' + index + '\\}', 'gm');
    const updatedValued = accumulator.replace(replacementPattern, arguments[index]);

    return updatedValued;
  }, initialValue);

  return formattedValue;
};

0
我有一个 Plunker,将其添加到字符串原型中: string.format 它不仅比其他示例短得多,而且更加灵活。
使用方式类似于 C# 版本:
var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy"); 
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array

此外,增加了使用名称和对象属性的支持

var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"}); 
//result: Meet you on Thursday, ask for Frank

你应该清理未使用的占位符。 var result1 = str1.format({day: "星期四"}); 星期四见,找{Person}。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接