zoukankan      html  css  js  c++  java
  • JS 替换

    JS 字符串有replace() 方法。但这个方法只会对匹配到的第一个字串替换。 如下例:

    var str = "wordwordwordword";
    var strNew = str.replace("word","Excel");
    alert(strNew);

    如果要全部替换的话,JS 没有提供replaceAll这样的方法。使用正则表可以达成Replace 的效果:

    g 的意义是:执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)。

    var str = "wordwordwordword";
    str = str.replace(/word/g,"Excel");

    以上写法有个类同的写法:

    str.replace(new RegExp("word","gm"),"Excel")

    g 执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)。

    m 执行多行匹配。

    除此之外,也可以添加 Stirng对象的原型方法:

    String.prototype.replaceAll = function(s1,s2){ 
    return this.replace(new RegExp(s1,"gm"),s2); 
    }

    这样就可以像使用replace 方法一样使用replaceAll了

    str.replaceAll("word","Excel");
  • 相关阅读:
    python条件判断之直接加数字
    pythontip题目解答
    twitter api取出的日期格式化
    MySQL Archive存储引擎
    Python Json序列化
    Python 装饰器
    Python 匿名函数
    Python 函数
    Python 字符编码
    Python 文件操作
  • 原文地址:https://www.cnblogs.com/blueskycc/p/5188940.html
Copyright © 2011-2022 走看看