zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    JDK13中将增加文本块特性
    java8新特性Lambda表达式为什么运行效率低
    Docker安装Mysql多版本
    Mysql中的降序索引底层实现
    GITHUB慢! 怎么办?
    程序员要搞明白CDN,这篇应该够了
    HTTP长连接
    Tomcat热部署与热加载
    Tomcat是一个Servlet容器?
    DPDK
  • 原文地址:https://www.cnblogs.com/untiring/p/14078544.html
Copyright © 2011-2022 走看看