js 字符串中的特殊字符全部替换成定义对象里面key对应的value值(进阶篇)
在上一篇文章中,初步介绍了字符串特殊字符的基础用法,js 字符串中的特殊字符全部替换成定义对象里面key对应的value值(基础篇)-CSDN博客可以回顾看一下。现在,进一步封装方法全局调用。
示例1
let textString = "你好!my name is ${name},l like ${hobby},this is a test string with special characters!";let userInfo = {name: 'Aotman_',hobby:"playing basketball"}let overString = textString.replace(/\$\{(.*?)\}/g,function(textString,i){console.log(textString, 'str');console.log(i, 'iii');return userInfo[i];});console.log(overString, '输出结果'); // 输出: "你好!my name is Aotman_,l like playing basketball,this is a test string with special characters!"
示例2
getReplaceStr(str, obj) {for (let key in obj) {str = str.replace(new RegExp('\\{\\{' + key + '\\}\\}', 'g'), obj[key])}return str}let userInfo = {name: 'Aotman_',hobby:"playing basketball"}let textString = `你好!my name is {{name}},l like {{hobby}},this is a test string with special characters!`console.log(this.getReplaceStr(textString, userInfo)); // 输出: "你好!my name is Aotman_,l like playing basketball,this is a test string with special characters!"
示例3
getReplaceStr(textString, userInfo) {return textString.replace(/{(.*?)}/g, (match, key) => {return typeof userInfo[key] !== 'undefined' ? userInfo[key] : match;});
}
const textString= "你好!my name is {name},l like {hobby},this is a test string with special characters!Hello, {name}! Welcome to {city}.";
const userInfo= {name: 'Aotman_',city:"Hang Zhou",hobby:"playing basketball"}
const overString= this.getReplaceStr(textString, userInfo);
console.log(overString); // 你好!my name is Aotman_,l like playing basketball,this is a test string with special characters!Hello, Aotman_! Welcome to Hang Zhou.
代码解析
1、函数定义:我们定义了一个名为 getReplaceStr的函数,它接受两个参数:textString和 userInfo。
2、正则表达式:/{(.*?)}/g 用于匹配字符串中的占位符。
3、替换逻辑:textString.replace(...) 方法将每个占位符替换为对象 userInfo 中相应的值。如果找不到对应的值,则保持原样。
进阶扩展:
getReplaceStr(textString) {const userInfo= {'name': 'Aotman_','city':"Hang Zhou",'hobby':"playing basketball",'.':"。"}return textString.trim().replace(new RegExp(Object.keys(userInfo).join('|'), 'g'), match => {return typeof userInfo[match] !== 'undefined' ? userInfo[match] : match})},
const textString = "你好!my name is name,l like hobby,this is a test string with special characters!Hello, name! Welcome to city.";
const result = this.getReplaceStr(textString);
console.log(result);//你好!my Aotman_ is Aotman_,l like playing basketball,this is a test string with special characters!Hello, Aotman_! Welcome to Hang Zhou。
结论
本文介绍了 JavaScript 的占位符替换方案,提供了灵活易懂的代码示例和实现步骤。无论是刚开始学习前端技术,还是正在从事前端开发工作,掌握字符串占位符替换的技巧都是十分重要的。希望通过本文,你能够更深入理解字符串处理的强大,提升开发技能,为未来的项目奠定坚实基础。如果你有任何问题或建议,欢迎留言讨论!