zoukankan      html  css  js  c++  java
  • 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.
    
  • 相关阅读:
    Length of Last Word
    Remove Duplicates from Sorted Array II
    Sum Root to Leaf Numbers
    Valid Parentheses
    Set Matrix Zeroes
    Symmetric Tree
    Unique Binary Search Trees
    110Balanced Binary Tree
    Match:Blue Jeans(POJ 3080)
    Match:Seek the Name, Seek the Fame(POJ 2752)
  • 原文地址:https://www.cnblogs.com/LoveTomato/p/8550352.html
Copyright © 2011-2022 走看看