zoukankan      html  css  js  c++  java
  • ES6--javascript判断一个字符串是否存在另一个字符串中

    es5中我们经常使用indexof()方法来判断一个字符串是否包含另外一个字符串中。

    如果存在则返回匹配到的第一个索引值。如果没有则返回 -1。所以,判断一个字符串是否包含另外一个字符串中只需要判断是否为-1就行。-1代表不存在。

    例如:

    let str = 'Hello World!';
    console.log(str.indexOf('H'));//0  str中"H"的出现的第一个索引为0
    console.log(str.indexOf('o'));//4  str中"o"第一个出现的位置的索引为4
    console.log(str.indexOf('a'));//-1 没找到,返回-1

    虽然Es5中该方法经常使用,但是Es6提供了更加便捷的方法。

    1. str.includes('');

    有返回true,没有返回false。也不用为记住-1而发愁了!!

    let str = 'Hello World!';
    console.log(str.includes('H'));//true
    console.log(str.includes('a'));//false

    2.startsWith()

    判断该字符串是否为某个字符串的首位。有就是true,不是就是false。

    let str = 'Hello World!';
    console.log(str.startsWith('H'));//true
    console.log(str.startsWith('Hello'));//true
    console.log(str.startsWith('e'));//false

    3.endsWith()

    和startsWith()相反。判断是否为末尾。

    let str = 'Hello World!';
    console.log(str.endsWith('!'));//true
    console.log(str.endsWith('d!'));//true
    console.log(str.endsWith('e'));//false

    这三个方法都支持第二个参数,表示看是搜索的位置。

    let str = 'Hello World!';
    console.log(str.includes('World',5));//true 从索引5(包含索引5)开始搜索
    console.log(str.includes('World',7));//false
    console.log(str.startsWith('lo',3))//true
    console.log(str.startsWith('H',3));//false
    console.log(str.endsWith('el',3));//true 
    endsWith()和上面两个不一样,它的第二个参数代表前几个。“Hel”,所以返回true
  • 相关阅读:
    【洛谷 P4166】 [SCOI2007]最大土地面积(凸包,旋转卡壳)
    专题
    【洛谷 P3299】 [SDOI2013]保护出题人 (凸包,三分,斜率优化)
    【洛谷 P3628】 [APIO2010]特别行动队 (斜率优化)
    $POJ1995$ $Raising$ $Modulo$ $Numbers$
    快速运算模板(未完待续)
    $Luogu$ $P1879$ $[USACO06NOV]$ 玉米田 $Corn Fields$
    [转载] $AT2444$ 题解
    [转载] $CF117B$ 题解
    [转载] $CF543B$ 题解
  • 原文地址:https://www.cnblogs.com/chinabin1993/p/8536591.html
Copyright © 2011-2022 走看看