登录
首页 >  文章 >  前端

JavaScript `stringreplace()` 有用案例

来源:dev.to

时间:2024-09-16 14:27:52 181浏览 收藏

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

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删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>