Notion app logo
Struggling to stay organized and effective? Learn to master your time and tasks with the Effectively Notion course!

Replace Multiple Instances of Pattern in JavaScript

How to replace multiple instances of a pattern in JavaScript with a regular expression.

2019-09-27

If you want to replace a pattern multiple times with the JavaScript replace method, you have to use a regular expression with the global flag.

Replacing the first found instance is achieved with the following:

"this is a string".replace(" ", "-");

Result:

"this-is a string"

When calling the replace method with a string as the first argument, it will only replace the first instance with the replace value (in this case "-").

Replacing all found instances is achieved with a regular expression and global flag:

"this is a string".replace(/ /g, "-");

Result:

"this-is-a-string"

When the replace method with a regular expression and the global flag, it will replace all instances with the replace value.

Photo of Chase Adams

Hey, I'm Chase. I help aspiring entrepreneurs and makers turn their ideas into digital products and apps.

Freebies

Vector Arrow Scribbles
banner image for figma vector arrows scribbles

A figma community project of vectorized hand-drawn arrows.

Go To Figma
Vector Line Scribbles
banner for figma vector line scribbles

A figma community project of vectorized hand-drawn lines.

Go To Figma
Vector Shape Scribbles
banner image of figma vector shapes scribbles

A figma community project of vectorized hand-drawn shapes.

Go To Figma

Subscribe to my Newsletter

Every other week I publish the Curiously Crafted newsletter.

In it, I explore the intersection of curiosity and craft: the people who make stuff, what they make and the way they pursue the craft of making.

Online

I'm on almost all social media as @curiouslychase.

The curious logo of Chase Adams: glasses and a bow tie.stay curious.