JavaScript `stringreplace()` 有用案例
来源:dev.to
2024-09-16 14:27:52
0浏览
收藏
一分耕耘,一分收获!既然打开了这篇文章《JavaScript `stringreplace()` 有用案例》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

1. 简单的字符串替换
替换第一次出现的子字符串。
let str = "hello world!";
let result = str.replace("world", "javascript");
// output: "hello javascript!"
2. 全局字符串替换
替换所有出现的子字符串,使用带有正则表达式的全局 (g) 标志。
let str = "hello world, world!"; let result = str.replace(/world/g, "javascript"); // output: "hello javascript, javascript!"
3. 不区分大小写的替换
您可以使用 i 标志使替换不区分大小写。
let str = "hello world, world!"; let result = str.replace(/world/gi, "javascript") // output: "hello javascript, javascript!"
4.替换整个单词(单词边界)
使用 b 单词边界仅替换整个单词。
let str = "this is a test word, test."; let result = str.replace(/\btest\b/, "success"); // output: "this is a success word, test."
替换所有出现的整个单词,使用全局标志。
let str = "this is a test word, test."; let result = str.replace(/\btest\b/g, "success"); // output: "this is a success word, success."
5. 使用函数进行替换
您可以将一个函数传递给replace(),以动态生成替换字符串。
let str = "the price is $10";
let result = str.replace(/\$\d+/g, (match) => {
return `$${parseint(match.substring(1)) * 2}`
});
// output: "the price is $20"
6. 通过替换捕获组
使用正则表达式,您可以捕获匹配的部分内容并在替换字符串中重用它们。
let str = "john smith"; let result = str.replace(/(\w+)\s(\w+)/, "$2, $1"); // output: "smith, john"
7. 转义特殊字符
如果您需要替换特殊字符,例如 .或*,您需要在正则表达式中转义它们。
let str = "price: 5.99"; let result = str.replace(/\./, ","); // output: "price: 5,99"
8. 替换非 ascii 字符
要替换不在 ascii 范围内的字符,您可以使用 unicode 属性。
let str = "héllo wörld"; let result = str.replace(/[^\x00-\x7f]/g, ""); // output: "hllo wrld"
9. 替换数字
您可以使用正则表达式替换数字(或数字组)。
let str = "contact: 123-456-7890";
let result = str.replace(/\d{3}/g, "***");
// output: "contact: ***-***-***0"
10. 使用 unicode 替换特殊字符
您还可以使用 unicode 转义序列来替换特殊字符。
let str = "I love ☕!"; let result = str.replace(/\u2615/g, "coffee"); // Output: "I love coffee!"
理论要掌握,实操不能落!以上关于《JavaScript `stringreplace()` 有用案例》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
Go 中错误处理的不同设计模式
- 上一篇
- Go 中错误处理的不同设计模式
- 下一篇
- win10日志文件怎么删除 win10日志文件删除路径在哪解析
查看更多
最新文章
-
- 文章 · 前端 | 1小时前 |
- JavaScript日期格式化方法全解析
- 325浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- HTML5边框定位不占位技巧
- 405浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- CSSLint优化技巧与样式提升方法
- 413浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- CSSSticky定位技巧:滚动与固定结合应用
- 293浏览 收藏
-
- 文章 · 前端 | 1小时前 |
- 统一图标风格,FontAwesome全站应用指南
- 356浏览 收藏
-
- 文章 · 前端 | 2小时前 |
- JavaScript动态加载模块技巧解析
- 119浏览 收藏
-
- 文章 · 前端 | 2小时前 |
- LinuxHelix加速技巧与重构指南
- 182浏览 收藏
-
- 文章 · 前端 | 2小时前 | 顶层await
- 顶层await用法详解与实战技巧
- 288浏览 收藏
-
- 文章 · 前端 | 2小时前 |
- 表单数据保留与自动清理技巧
- 120浏览 收藏
-
- 文章 · 前端 | 2小时前 |
- EventLoop机制解析与执行顺序控制技巧
- 392浏览 收藏
-
- 文章 · 前端 | 2小时前 |
- Tailwind任意值类解决方法详解
- 321浏览 收藏
-
2. CSS 样式使用 ::after 伪元素来在图片上叠加文字:
.im">

