我正在尝试将一些JavaScript代码从MicrosoftAjax迁移到JQuery。 我使用MicrosoftAjax中流行的.net方法的JavaScript等效方法,例如String.format(),String.startsWith()等。 在jQuery中是否有与它们相当的方法?
我正在尝试将一些JavaScript代码从MicrosoftAjax迁移到JQuery。 我使用MicrosoftAjax中流行的.net方法的JavaScript等效方法,例如String.format(),String.startsWith()等。 在jQuery中是否有与它们相当的方法?
使用函数式编程:
// '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;
};
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