当前位置: 首页 > news >正文

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 的占位符替换方案,提供了灵活易懂的代码示例和实现步骤。无论是刚开始学习前端技术,还是正在从事前端开发工作,掌握字符串占位符替换的技巧都是十分重要的。希望通过本文,你能够更深入理解字符串处理的强大,提升开发技能,为未来的项目奠定坚实基础。如果你有任何问题或建议,欢迎留言讨论!

相关文章:

  • Python | 赤道频散关系图
  • 【Redis】SDS结构
  • 图形化编程平台的破局之道:从工具同质化到生态差异化
  • 从MCU到SoC的开发思维转变
  • 2024年北理工Python123第六章测验题整理
  • React 播客专栏 Vol.9|React + TypeScript 项目该怎么起步?从 CRA 到配置全流程
  • 2025年Energy SCI1区TOP,改进雪消融优化算法ISAO+电池健康状态估计,深度解析+性能实测
  • UE RPG游戏开发练手 第二十一课 使用C++代码实现装备武器
  • C/C++ 内存管理深度解析:从内存分布到实践应用(malloc和new,free和delete的对比与使用,定位 new )
  • 如何使用 WebBrowserPassView 查看所有浏览器密码?
  • 用户态到内核态:Linux信号传递的九重门(二)
  • 动手学深度学习12.4.硬件-笔记练习(PyTorch)
  • 应急响应靶机——WhereIS?
  • C# 中 static的使用
  • Mysql的索引,慢查询和数据库表的设计以及乐观锁和悲观锁
  • DeepSeek | AI需求分析
  • 从零开始的python学习(七)P89+P90+P91+P92+P93+P94
  • Tauri(2.5.1)+Leptos(0.7.8)开发桌面应用--程序启动界面
  • Python基础:类的深拷贝与浅拷贝-->with语句的使用及三个库:matplotlib基本画图-->pandas之Series创建
  • HDFS概述
  • 中国人民抗日战争暨世界反法西斯战争胜利80周年纪念活动标识发布
  • 西藏日喀则市拉孜县发生5.5级地震,震感明显部分人被晃醒
  • 默茨首访聚焦欧洲,欲推欧洲防务自主
  • 中山大学人类学系原系主任冯家骏逝世,享年95岁
  • 广西百色通报:极端强对流天气致墙体倒塌,3人遇难7人受伤
  • 巴基斯坦称对印度发起军事行动