Home > Web Front-end > JS Tutorial > How to Determine if a JavaScript String Starts With a Specific Substring?

How to Determine if a JavaScript String Starts With a Specific Substring?

Mary-Kate Olsen
Release: 2024-12-12 13:30:16
Original
749 people have browsed it

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;
  };
}
Copy after login

ES6-Shim:

require('es6-shim');
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template