需求:用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.