Javascript — string replace all without Regex

Yan Cui
theburningmonk.com
Published in
1 min readApr 23, 2016

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?

--

--

Yan Cui
theburningmonk.com

AWS Serverless Hero. Follow me to learn practical tips and best practices for AWS and Serverless.