记录一个开发中所犯的错误
需求: 用 js 将字符串中的某些子字符串替换为指定的新字符串
实现思路: 印象中 js 字符串替换有 replace 方法, replace 方法接收两个参数, 第一个为要替换的子字符串或正则匹配模式, 第二个参数为新字符串自己对正则不熟, 认为用字符串能满足需求
简单测试
- var str="apples are round";
- var newStr = str.replace(apples,oranges)
- //newStr 值为: oranges are round
运行结果正确, 到项目中错了, 错误原因: 当 replace 方法的第一个参数为字符串时, 仅仅是第一个匹配会被替换
再次测试
- var str1="apples are round, and apples are juicy.";
- var newStr1 = str1.replace(apples,oranges);
- //newStr1 值为: oranges are round, and apples are juicy.
运行结果与期望不符, 只被替换一个
解决: 还需要使用正则表达式: 正则表达式包含有全局替换 (g) 和忽略大小写 (i) 的选项
- var str2="apples are round, and apples are juicy.";
- var newStr2 = str2.replace(/apples/g,oranges);
- //newStr2 值为: oranges are round, and oranges are juicy.
js 字符串替换(replace)
来源: http://www.bubuko.com/infodetail-2525205.html