首页 > web前端 > js教程 > 正文

JavaScript `stringreplace()` 有用案例

DDD
发布: 2024-09-13 22:21:09
转载
291人浏览过

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()` 有用案例的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号