教你查找字元串中包含某字元串「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

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/269349.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-16 13:15
下一篇 2024-12-16 13:15

相關推薦

發表回復

登錄後才能評論