Explain Codes LogoExplain Codes Logo

Check if string begins with something?

javascript
prompt-engineering
functions
best-practices
Alex KataevbyAlex Kataev·Nov 30, 2024
TLDR

startsWith() is your go-to function for verifying if a string begins with a specific substring in JavaScript:

let result = "Hello World!".startsWith("Hello"); // true, "Hello" indeed comes first!

Stuck with older JavaScript versions? Fear not, indexOf() is your lifesaver:

let result = "Hello World!".indexOf("Hello") === 0; // true - "Hello" is at index 0!

Leveraging substring for backward compatibility

In navigating legacy browsers or environments, where startsWith() or indexOf() aren't your allies, you might find substring() to be a knight in shining armor. It elegantly extracts parts of a string:

let str = "Hello World!"; let pattern = "Hello"; let result = str.substring(0, pattern.length) === pattern; // true, they say Hello at the same time!

Heads up: Dive into the MDN documentation linked in the References section to wrap your head around substring() method.

Regular expressions: Because life isn't always simple

For times when you need more power and control, be it complex patterns or more, regular expressions (regex) are your Holy Grail:

let pathname = "/sub/123/example"; let result = pathname.match(/^\/sub\/123/); // returns non-null if matches, just like you after reading this answer!

In regex, ^ asserts the position at start of the string, and \/ is an escaped slash - just what the doctor ordered for URL pattern matching!

Golden point: Don't forget to escape special characters in regex for precision.

Keeping code DRY with functions

Who doesn’t like reusability? Meet our in-house hero - a beginsWith function that works beautifully with different strings and keeps your code DRY:

function beginsWith(str, pattern) { return str.indexOf(pattern) === 0; // jQuery devs be like: "I am back, baby!" } // How to use: if (beginsWith(window.location.pathname, "/sub/1")) { // Add a class, do a dance, the world is your oyster! }

Did you notice?: This function improves code readability and reusability. Say goodbye to redundancy!

Treading carefully: Common pitfalls and solutions

In the wild world of URL paths or file extensions, tiny deviations such as case sensitivity or trailing slashes can throw a spanner in your works.

  • Case Sensitivity: Harmonize your strings using toLowerCase() or toUpperCase() before you start comparing.
  • Trailing Slashes: Leverage trim() to bid adieu to unwanted whitespace, or replace(/\/*$/, '') to get rid of those sneaky trailing slashes.

Make it readable: Custom string prototypes are here!

To enhance readability and expressiveness, consider augmenting the String prototype:

String.prototype.beginsWith = function(pattern) { return this.startsWith(pattern); }; if ("My String".beginsWith("My")) { // Match confirmed, prepare for confetti shower! }

Code Red: Modifying prototypes can lead to unexpected results if code depends on enumerating properties or methods of built-in objects.

HTML styling goes dynamic

Assign classes to elements based on how your strings hold up in comparison, achieving dynamic styling while you're at it:

if (pathname.startsWith("/sub/1")) { document.body.className += " sub-category-1"; // quietly giving your HTML a makeover }

This technique opens doors for dynamic theming or conditional content mutation, all without touching the sacred HTML.