美文网首页nodejs学习
nodejs查询字符串是否包含另外一个字符串中

nodejs查询字符串是否包含另外一个字符串中

作者: 村东头元旦家 | 来源:发表于2018-12-05 14:49 被阅读58次

    传统上,JavaScript只有indexOf方法,可以用来确定一个字符串是否包含在另外一个字符串中。es6又提供了三种新的方法。

    -includes(): 返回布尔值,表示是否找到了参数字符串。

    -startsWith():返回布尔值,表示参数字符串是否在源字符串的头部。

    -endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。

    let

    s = "Hello World!";

    let a = s.startsWith("Hello");

    let b = s.endsWith("!");

    let c = s.includes('o');

    console.log("------a=", a, '-----b=', b, '----c=', c);

    //------a= true -----b= true ----c= true

    这三种方法还支持第二个参数,表示开始搜索的位置。

    let s1 = "Hello World!";

    let a1 = s.startsWith("Hello", 2);

    let b1 = s.endsWith("World", 6);

    let c1 = s.includes('', 6);

    console.log("------a1=", a1, '-----b1=', b1, '----c1=', c1);

    //------a1= false -----b1= false ----c1= true

    endsWith的行为与其他两个方法有所不同。它针对前n个字符,而其他两个方法针对从第n个位置直到字符串结束。

    相关文章

      网友评论

        本文标题:nodejs查询字符串是否包含另外一个字符串中

        本文链接:https://www.haomeiwen.com/subject/detwcqtx.html