How to check whether a string contains a substring in JavaScript?
阿新 • • 發佈:2021-11-03
How to check whether a string contains a substring in JavaScript?
回答1
CMAScript6 introduced String.prototype.includes
:
const string = "foo";
const substring = "oo";
console.log(string.includes(substring)); // true
includes
doesn’t have InternetExplorer support, though. In ECMAScript5 or older environments, use String.prototype.indexOf
, which returns -1 when a substring cannot be found:
var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1); // true
評論:
While this is a good answer, and the OP never requested for a "case-sensitive" search, it should be noted that includes
performs a case-sensitive search.
回答2
There is a String.prototype.includes
in ES6:
"potato".includes("to");
> true
Note that this does not work in Internet Explorer or some other old browsers with no or incomplete ES6 support. To make it work in old browsers, you may wish to use a transpiler like Babel, a shim library like es6-shim, or this polyfill from MDN:
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;
}
};
}