Javascript – string replace all without Regex

Yan Cui

I help clients go faster for less using serverless technologies.

This article is brought to you by

Hookdeck: The Serverless Event Gateway

Hookdeck is a reliable and scalable serverless event gateway for sending, receiving, authenticating, transforming, filtering, and routing events between services in your event-driven architecture.

Learn more

I have been working with Node.js and Serverless heavily. It’s the first time I’ve really spent serious amount of time in Javascript, and I’m making plenty of beginner mistakes and learning lots.

One peculiar thing I find in Javascript is that String.replace only replaces the first instance of the substring, unless you use a Regex. Fortunately I found a clever little pattern to do this without Regex : String.split(subString).join(replaceString).

So suppose you want to remove the hyphen (-) in an AWS region name, you could write:

let region = ‘eu-west-1’;

let regionNoHyphen = region.split(‘-‘).join(”);

Much easier than using Regex, wouldn’t you agree?

Whenever you’re ready, here are 4 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. Do you want to know how to test serverless architectures with a fast dev & test loop? Check out my latest course, Testing Serverless Architectures and learn the smart way to test serverless.
  3. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  4. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

3 thoughts on “Javascript – string replace all without Regex”

  1. I think once you get used to Regex in JS it isn’t too bad.

    "y-e-p".replace(/-/g,"") // => yep

  2. Yeah, regex is great… if you want to replace a known substring. Now try writing a replaceall function which must be able to replace all possible substrings with another, regardless of the contents of that substring! Now you first have to escape your replace string, and then make sure your escape is correct, and then that it remains correct with later “improvements” to the JS’s regex specification…

    You had a problem. You solved it with a regex. Now you have two problems.

    The function in the article works for all strings, and doesn’t give you any headaches.

Leave a Comment

Your email address will not be published. Required fields are marked *