How to check if a string “StartsWith” another string?

You can use ECMAScript 6’s String.prototype.startsWith() method, but it’s not yet supported in all browsers. You’ll want to use a shim/polyfill to add it on browsers that don’t support it. Creating an implementation that complies with all the details laid out in the spec is a little complicated. If you want a faithful shim, use either:

  • Matthias Bynens’s String.prototype.startsWith shim, or
  • The es6-shim, which shims as much of the ES6 spec as possible, including String.prototype.startsWith.

Once you’ve shimmed the method (or if you’re only supporting browsers and JavaScript engines that already have it), you can use it like this:

   console.log("Hello World!".startsWith("He")); // true
    
var haystack = "Hello world";
var prefix = 'orl';
console.log(haystack.startsWith(prefix)); // false

Leave a Comment