前进中的蜗牛

番茄大叔

水滴穿石,非一日之功;没有量变,何来质变。

js字符串替换(replace)

记录一个开发中所犯的错误。

  1. 需求:用js将字符串中的某些子字符串替换为指定的新字符串
  2. 实现思路:印象中js字符串替换有replace方法,replace方法接收两个参数,第一个为要替换的子字符串或正则匹配模式,第二个参数为新字符串。自己对正则不熟,认为用字符串能满足需求。
    简单测试
var str="apples are round";
var newStr = str.replace('apples','oranges')
//newStr 值为:oranges are round
  1. 运行结果正确,到项目中错了,错误原因:当replace方法的第一个参数为字符串时,仅仅是第一个匹配会被替换。
    再次测试
var str1="apples are round, and apples are juicy.";
var newStr1 = str1.replace('apples','oranges');
//newStr1 值为:oranges are round, and apples are juicy.
  1. 运行结果与期望不符,只被替换一个。
  2. 解决:还需要使用正则表达式:正则表达式包含有全局替换(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.
posted @ 2018-03-12 17:10  LoveTomato  阅读(651)  评论(0编辑  收藏  举报