首頁  >  文章  >  web前端  >  es6怎麼判斷字串中是否有某個字串

es6怎麼判斷字串中是否有某個字串

青灯夜游
青灯夜游原創
2023-01-16 17:23:044082瀏覽

判斷方法:1、利用includes(),語法“str.includes(searchString[, position])”;2、利用indexOf(),語法“str.indexOf(substring)”,如果返回“ -1」則沒有;3、利用test()、match()或search()配合正規表示式查找,語法「exp.test(str)」、「str.match(exp)」。

es6怎麼判斷字串中是否有某個字串

本教學操作環境:windows7系統、ECMAScript 6版、Dell G3電腦。

es6判斷字串是否包含子字串的方法

#方法1:利用includes()函數

ES6的字串新增了includes方法,我們可以用它來判斷是否包含子字串。

str.includes(searchString[, position])
  • searchString:查詢的子字串

  • #position:可選,開始搜尋的位置,預設為0

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

要注意的是,includes方法是會區分大小寫。

對於不支援es6的瀏覽器,可以加入es6-shim,如:

require('es6-shim')

方法2:利用indexOf()函數

##indexOf是我們比較常用到判斷是否包含子字串的方法。如果包含子字串,傳回子字串的索引,否則傳回-1。

var string = "foo",
    substring = "oo";
if(string.indexOf(substring) == -1) {
  console.log("不包含子字符串")
} else {
  console.log("包含子字符串")
}

方法3:利用正規表示式

使用正規表示式有三種方式:test,match,search

1、test

var string = "foo",
    exp = /oo/;
var result = exp.test(string);

test傳回的是一個布林值。存在回傳true,否則回傳false。

注意test函數呼叫者是正規表示式。

2、match

var string = "foo",
    exp = /oo/;
var result = string.match(exp);
console.log(result);

輸出結果:

["oo", index: 1, input: "foo"]

呼叫者是字串,如果符合到傳回數組,包含了符合到的內容:正規表示式, index和input。

3、search

var string = "foo",
    exp = /oo/;
var result = string.search(exp);

傳回的是搜尋到的子字串的索引,搜尋不到返回-1

【相關推薦:

javascript影片教學web前端#

以上是es6怎麼判斷字串中是否有某個字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn