Home > Web Front-end > JS Tutorial > How Can I Check if One String Starts With Another in JavaScript?

How Can I Check if One String Starts With Another in JavaScript?

DDD
Release: 2024-12-15 19:01:10
Original
309 people have browsed it

How Can I Check if One String Starts With Another in JavaScript?

Determining String Precedence with "StartsWith"

Question: How can I ascertain if one string initiates with another in JavaScript, akin to the String.StartsWith method in C#?

JavaScript Equivalent to C#'s String.StartsWith

Prior to ECMAScript 2015 (ES6), JavaScript lacked a native method similar to String.StartsWith. However, ES6 introduced the String.prototype.startsWith() method.

Browser Support:

Note that as of this writing (2015), comprehensive browser support for String.prototype.startsWith() remains insufficient. Therefore, support may be required in browsers that lack native implementation.

Shimming for Unsupported Browsers:

For browsers without native String.prototype.startsWith() support, shims or polyfills can be utilized to provide functionality. Two recommended options are:

  • Matthias Bynens's String.prototype.startsWith shim
  • The es6-shim, which incorporates a wide range of ES6 features, including String.prototype.startsWith().

Usage after Shimming or for Supported Browsers:

Once method support is ensured, String.prototype.startsWith() can be employed 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 Can I Check if One String Starts With Another in JavaScript?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template