<menu id="ycqsw"></menu><nav id="ycqsw"><code id="ycqsw"></code></nav>
<dd id="ycqsw"><menu id="ycqsw"></menu></dd>
  • <nav id="ycqsw"></nav>
    <menu id="ycqsw"><strong id="ycqsw"></strong></menu>
    <xmp id="ycqsw"><nav id="ycqsw"></nav>
  • js判斷字符串包含某個字符(教你查找字符串中包含某字符串)


    includes 函數 語法

    str.includes(searchString[, position])

    includes() 方法用于判斷一個字符串是否包含在另一個字符串中,根據情況返回 true 或 false。

    includes() 方法是區分大小寫的,例如,下面的表達式會返回 false

    'Blue Whale'.includes('blue'); // returns false

    兼容補丁(polyfill)

    if (!String.prototype.includes) {
      String.prototype.includes = function(search, start) {
        'use strict';
        if (typeof start !== 'number') {
          start = 0;
        }
    
        if (start + search.length > this.length) {
          return false;
        } else {
          return this.indexOf(search, start) !== -1;
        }
      };
    }

    示例

    var str = 'To be, or not to be, that is the question.';
    
    console.log(str.includes('To be'));       // true
    console.log(str.includes('question'));    // true
    console.log(str.includes('nonexistent')); // false
    console.log(str.includes('To be', 1));    // false
    console.log(str.includes('TO BE'));       // false

    indexOf 函數語法

    str.indexOf(searchValue [, fromIndex])

    參數

    searchValue

    要被查找的字符串值。

    如果沒有提供確切地提供字符串,searchValue 會被強制設置為 “undefined”, 然后在當前字符串中查找這個值。

    舉個例子:’undefined’.indexOf() 將會返回0,因為 undefined 在位置0處被找到,但是 ‘undefine’.indexOf() 將會返回 -1 ,因為字符串 ‘undefined’ 未被找到。

    fromIndex 可選

    數字表示開始查找的位置??梢允侨我庹麛?,默認值為 0。

    如果 fromIndex 的值小于 0,或者大于 str.length ,那么查找分別從 0 和str.length 開始。

    舉個例子,’hello world’.indexOf(‘o’, -5) 返回 4 ,因為它是從位置0處開始查找,然后 o 在位置4處被找到。另一方面,’hello world’.indexOf(‘o’, 11) (或 fromIndex 填入任何大于11的值)將會返回 -1 ,因為開始查找的位置11處,已經是這個字符串的結尾了。

    示例

    var anyString = "Brave new world";
    
    console.log("The index of the first w from the beginning is " + anyString.indexOf("w"));
    // logs 8
    console.log("The index of the first w from the end is " + anyString.lastIndexOf("w"));
    // logs 10
    
    console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));
    // logs 6
    console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
    // logs 6
    

    版權聲明:本文內容由互聯網用戶自發貢獻,該文觀點僅代表作者本人。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如發現本站有涉嫌抄襲侵權/違法違規的內容, 請發送郵件至 舉報,一經查實,本站將立刻刪除。

    發表評論

    登錄后才能評論
    国产精品区一区二区免费