• js 查找字符串中是否包含指定的字符串


    1、indexOf()

    var str = "123";
    console.log(str.indexOf("3") != -1 ); // true

    indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。如果要检索的字符串值没有找到,则该方法返回 -1

    2、includes()

    var str = "Hello world, welcome to the Runoob。";
    var n = str.includes("world"); //true

    includes() 方法用于判断字符串是否包含指定的子字符串,如果找到匹配的字符串则返回 true,否则返回 false。注意: includes() 方法区分大小写。

    3、search()

    var str="Visit W3School!"
    console.log(str.search(/W3School/)) //6
     
    var str="Visit W3School!"
    console.log(str.search('W3School')) //6

    search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。如果匹配到字符串则返回,字符串所在索引。

    4、match()

    var str="The rain in SPAIN stays mainly in the plain";
    var n=str.match(/ain/g); // ain,ain,ain

    match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。注意: includes() 方法不区分大小写。

    5、test()

    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
        console.log("移动")
    } else {
        console.log("PC")
    }
     
    var str="Hello world!";
    //查找"Hello"
    var patt=/Hello/g;
    var result=patt.test(str);
    console.log(result) // true

    test() 方法用于检测一个字符串是否匹配某个模式。如果字符串中有匹配的值返回 true ,否则返回 false。

    6、exec()

    var str="Hello world!";
    //查找"Hello"
    var patt=/Hello/g;
    var result=patt.exec(str);
    console.log(result) // Hello

    exec() 方法用于检索字符串中的正则表达式的匹配。如果字符串中有匹配的值返回该匹配值,否则返回 null。

    参考:https://www.cnblogs.com/untiring/p/14078544.html

  • 相关阅读:
    Oracle左连接、右连接、全外连接以及(+)号用法
    linux中游戏好玩
    python之allure报告
    UI自动化之元素定位(xpath、css)
    expected_conditions模块提供了判断页面元素的16种方法
    安全测试1_Web知识简介
    零基础学习python_easygui(35课)
    jmeter通过if控制器控制业务比例
    系统异常设计
    kafka 消息队列
  • 原文地址:https://www.cnblogs.com/chen-cheng/p/14654576.html
Copyright © 2020-2023  润新知