zoukankan      html  css  js  c++  java
  • 正则表达式的使用

    RegExp是正则表达式的缩写。

    当检索某个文本时,可以使用一种模式来描述要检索的内容。RegExp就是这种模式。

    test方法

    test()方法检索字符串中的指定值。返回值是true或false。

    var pat = /m/;

    var str = “this m id code”;

    console.log(pat.test(str));//true

    exec方法

    exec()方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回null。

    var pat = /hello/;

    console.log(pat.exec(“oh hello world”));//返回hello

    正则表达式类型

    /pattern/attributes

    参数attributes 是一个可选的字符串,常用属性“g”,”i”,分别用于指定全局匹配、区分大小写的匹配。

    字符串正则

    1.search  字符串查找

    var  str = “hello world!”;

    console.log(str.search(/World/));//-1

    console.log(str.search(/World/i));//6

    2.match  字符串匹配

    var str = “1 str 333 eqeef 33”;

    console.log(str.match(/d+/));//[1]

    console.log(str.match(/d+/g));//[1,333,33]

    3.replace 字符串替换

    var str = “hello world,world is nice!”;

    console.log(str.replace(/world/,”xu”));//hello xu,world is nice!

    console.log(str.replace(/world/ig,”xu”));//hello xu,xu is nice!

    4.split  字符串分割

    var str = “hello xu,oh i am qian”;
    console.log(str.split(“”));//[“h”, “e”, “l”, “l”, “o”, ” “, “x”, “u”, “,”, “o”, “h”, ” “, “i”, ” “, “a”, “m”, ” “, “q”, “i”, “a”, “n”]
    console.log(str.split(/s+/));//[“hello”, “xu,oh”, “i”, “am”, “qian”]

  • 相关阅读:
    Java项目中读取properties文件,以及六种获取路径的方法
    在eclipse中使用JUnit4,以及使用JUnit4进行单元测试的技巧
    [Evernote]印象笔记使用经验技巧
    使用Word2010发布博客文章
    Win7/8 绿色软件开机启动
    常见笔试题
    排序
    数据库知识归纳(索引)
    数据库知识归纳(事务)
    Redis
  • 原文地址:https://www.cnblogs.com/qianrong/p/8532221.html
Copyright © 2011-2022 走看看