Home >Web Front-end >JS Tutorial >How to Determine if a JavaScript String Starts With a Specific Substring?
How to Check if a String Starts With Another String in JavaScript
The String.prototype.startsWith() method in JavaScript allows you to check if a string begins with a specified substring.
Prior to ES6, you could use a polyfill to add startsWith() functionality to unsupported browsers:
Matthias Bynens's String.prototype.startsWith Shim:
if (!String.prototype.startsWith) { String.prototype.startsWith = function(searchString, position) { position = position || 0; return this.substr(position, searchString.length) === searchString; }; }
ES6-Shim:
require('es6-shim');
Usage:
Once you have shimmed startsWith() or are using a compatible browser, you can use it as follows:
console.log("Hello World!".startsWith("He")); // true var haystack = "Hello world"; var prefix = 'orl'; console.log(haystack.startsWith(prefix)); // false
The above is the detailed content of How to Determine if a JavaScript String Starts With a Specific Substring?. For more information, please follow other related articles on the PHP Chinese website!