Javascript – string replace all without Regex

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?

2 Comments

  1. jon49   •  

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

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

  2. Yan Cui   •  

    awesome! thank you for that, didn’t realise there’s a regex shorthand

Leave a Reply

Your email address will not be published.