Chase AdamsChase Adams
AboutContentPromptsPlayground

Replace Multiple Instances of Pattern in JavaScript

Essays and updates on product, engineering, and AI by Chase Adams.

1 minute read

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.

First Cohort
No Coding Experience Required

Build Your Website with AI—No Code Required

Learn to create and deploy professional websites using ChatGPT and Claude. Go from complete beginner to confident website builder.

Start Building Today

Post Details

Published
Sep 26, 2019
Category
Engineering
Share
Ask ChatGPT
Ask Claude

Similar Posts

Inspect a Collection of Objects in Javascript with console.table

Inspect a Collection of Objects in Javascript with console.table

in JavaScript

AboutAI Workflow SpecContentStacksNewsletterPromptsRSS

Ask me anything

Loading...

Hi! Ask me anything about Chase's work.

I can answer questions based on his blog posts and articles.

Experimental: This chat is a side project I work on in my free time. Responses may vary in quality and accuracy.