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
Mary-Kate OlsenOriginal
2024-12-12 13:30:16752browse

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!

Statement:
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