原生JS实现String.Format

88 阅读1分钟
// 将 Format 方法添加到字符串的原型上, 让所有的字符串都能调用这个方法
String.prototype.Format = function(...arg){
    let str = this; // this的值是当前调用Format 方法的字符串内容
	const regArr = str.match(/{\d+}/g);  // 正则获取到字符串里面的占位符
	// 将得到的占位符数组进行排序 从低到高
	regArr.sort((a, b) => {
		// {0} => 0  匹配占位符的数字
		const regA = a.match(/\d+/g)[0];
		const regB = b.match(/\d+/g)[0];
		return regA - regB;
	});
	// 遍历得到的占位符数组,并将字符串中 对应的占位符给替换掉
    regArr.map((row)=>{
        const regIndex = row.match(/\d+/g)[0];
        arg[regIndex] &&( str = str.replaceAll(row, arg[regIndex]));
    })
	// 将格式化之后的内容返回
	return str;
};

let regStr = "select {2} FROM testTable WHERE id = '{0}' and BARCODE = '{10}'--{11}--{6}";

console.log("原",regStr);
const resultStr = regStr.Format(123, 456, "*",789,147,258,369,1,2,3,"q1we","asdf","zxcxc");
console.log("格式化",resultStr);

运行结果
原 select {2} FROM testTable WHERE id = ‘{0}’ and BARCODE = ‘{10}’–{11}–{6}
格式化 select * FROM testTable WHERE id = ‘123’ and BARCODE = ‘q1we’–asdf–369

截止:2024-1-18 运行正常