码迷,mamicode.com
首页 > Web开发 > 详细

js字符串替换(replace)

时间:2018-03-12 18:39:49      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:开发   第一个   ace   指定   and   blog   大小写   post   oranges   

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

  1. 需求:用js将字符串中的某些子字符串替换为指定的新字符串
  2. 实现思路:印象中js字符串替换有replace方法,replace方法接收两个参数,第一个为要替换的子字符串或正则匹配模式,第二个参数为新字符串。自己对正则不熟,认为用字符串能满足需求。
    简单测试

    var str="apples are round";
    var newStr = str.replace(‘apples‘,‘oranges‘)
    //newStr 值为:oranges are round
  3. 运行结果正确,到项目中错了,错误原因:当replace方法的第一个参数为字符串时,仅仅是第一个匹配会被替换。
    再次测试

    var str1="apples are round, and apples are juicy.";
    var newStr1 = str1.replace(‘apples‘,‘oranges‘);
    //newStr1 值为:oranges are round, and apples are juicy.
  4. 运行结果与期望不符,只被替换一个。
  5. 解决:还需要使用正则表达式:正则表达式包含有全局替换(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)

标签:开发   第一个   ace   指定   and   blog   大小写   post   oranges   

原文地址:https://www.cnblogs.com/LoveTomato/p/8550352.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!