如何在JavaScript中檢查字串是否包含子字串?
這裡有一個可用方法列表:
- (ES6) includes
var string = "foo", substring = "oo"; string.includes(substring);
- ES5 and older indexOf
var string = "foo", substring = "oo"; string.indexOf(substring) !== -1; String.prototype.indexOf returns the position of the string in the other string. If not found, it will return -1.
- search
var string = "foo", expr = /oo/; string.search(expr);
- lodash includes
var string = "foo", substring = "oo"; _.includes(string, substring);
- RegExp
var string = "foo", expr = /oo/;// no quotes here expr.test(string);
- Match
var string = "foo", expr = /oo/; string.match(expr);
效能測試表明,如果速度很重要,indexOf可能是最好的選擇。
轉載請註明出處:
http://zgljl2012.com/ru-he-zai-javascriptzhong-jian-cha-zi-fu-chuan-shi-fou-bao-han-zi-zi-fu-chuan/