Explain Codes LogoExplain Codes Logo

How to check if a string "StartsWith" another string?

javascript
starts-with
polyfill
performance
Anton ShumikhinbyAnton Shumikhin·Aug 19, 2024
TLDR

Use the JavaScript startsWith() method to check if a string begins with specific characters:

// Does "Java" sounds like a coffee variant? console.log("JavaScript".startsWith("Java")); // prints true

Compatibility considerations: Welcoming the Oldies

Unfortunately, not all browsers are prompt when it comes to updating their JS standards. In simple terms, legacy browsers might throw a tantrum when you use startsWith(). But fret not! Polyfills have got your back!

A polyfill is essentially a piece of code that is used to provide modern functionality on older browsers that do not natively support it.

// Preventing legacy browsers from feeling left out if (!String.prototype.startsWith) { String.prototype.startsWith = function(search, pos) { return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; }; }

This code ensures that startsWith() function is made available as a method in the String object. So every text you create will have access to this method.

Delving deeper: Edge cases and optimization

Tested and trusted: Vintage approaches

For those living in the past (older browsers), here are some time-honoured methods that also check if a string starts with a specified prefix:

  • The good old indexOf() method:
// Legend has it, if 'prefix' is in 'text' right at index zero, it's a match! var text = "Hello world"; var prefix = "Hel"; console.log(text.indexOf(prefix) === 0); // prints true
  • My personal favourite, lastIndexOf() method:
// Finds 'prefix' from the end, but starts at index zero. Sounds counter-intuitive, but works ;) var text = "Hello world"; var prefix = "He"; console.log(text.lastIndexOf(prefix, 0) === 0); // prints true
  • Oldie goldie substring():
// Chops off a piece of 'text', compares it with 'prefix'. If they are same, we got a match! var text = "Hello world"; var prefix = "Hel"; console.log(text.substring(0, prefix.length) === prefix); // prints true

Dynamic RegExp: Wrestle with special cases

For variable prefixes or those containing special characters in RegExp, carefully escape those characters:

// RegExp can be tricky beast to tame, so we escape. There's no shame in retreating ;) function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } var text = "Hello world"; var prefix = "He.*"; // Without escape, the dot(.) and asterisk(*) hold special meaning in RegExp var escapedPrefix = escapeRegExp(prefix); var regex = new RegExp('^' + escapedPrefix); console.log(regex.test(text)); // evalutes to false, because 'He.*' is treated literally

Jostling with giants: Performance tug-of-war

Need for speed? Code execution performance does matter when you're dealing with large datasets. These bypasses like indexOf() and lastIndexOf() may give faster results than startsWith() in some JS engine implementations.

// I'm all for speed. The faster, the better ;) var text = "Hello world"; var prefix = "He"; console.log(text.lastIndexOf(prefix, 0) === 0); // prints true