How to replace all occurrences of a string in javascript?

Regular Expressions (also called RegEx or RegExp) are a powerful way to analyze text. With RegEx, you can match strings at points that match specific characters (for example, JavaScript) or patterns (for example, NumberStringSymbol - 3a&).

Bạn đang xem: How to replace all occurrences of a string in javascript?

The .replace method is used on strings in JavaScript khổng lồ replace parts of string with characters. It is often used lượt thích so:

const str = "JavaScript";const newStr = str.replace("ava", "-");console.log(newStr);// J-ScriptAs you can see above sầu, the replace method accepts two arguments: the string khổng lồ be replaced, and what the string would be replaced with.

Here is where Regex comes in.

The use of .replace above is limited: the characters to be replaced are known - "ava". What if we"re concerned with a pattern instead? Maybe, a number, two letters, và the word "foo" or three symbols used together?

The .replace method used with RegEx can achieve sầu this. RegEx can be effectively used khổng lồ recreate patterns. So combining this with .replace means we can replace patterns & not just exact characters.

How khổng lồ use RegEx with .replace in JavaScript

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/. This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

Here"s an example:

// matches a number, some characters và another numberconst reg = /d.*d/const str = "Java3foobar4Script"const newStr = str.replace(reg, "-");console.log(newStr);// "Java-Script"The string 3foobar4 matches the regex /d.*d/, so it is replaced.

What if we wanted to perform replacements at multiple places?

Regex already offers that with the g (global) flag, & the same can be used with replace. Here"s how:

const reg = /d3/gconst str = "Java323Scr995ip4894545t";const newStr = str.replace(reg, "");console.log(newStr);// JavaScrip5t// 5 didn"t pass the chạy thử :(The regex matches parts of the string that are exactly 3 consecutive numbers. 323 matches it, 995 matches it, 489 matches it, and 454 matches it. But the last 5 does not match the pattern.

Xem thêm: Giá Phần Mềm Yanxiu Mold - Giá Phần Mềm Nx Mold Thiết Kế Khuôn

The result is that JavaScrip5t shows how the patterns are correctly matched and replaces with the new substring (an empty string).

The case flag - i can also be used. This means you can replace case-insensitive patterns. Here"s how it is used:

const reg1 = /dA/const reg2 = /dA/iconst str = "Jav5ascript"const newStr1 = str.replace(reg1, "--");const newStr2 = str.replace(reg2, "--");console.log(newStr1) // Jav5ascriptconsole.log(newStr2) // Jav--script..5a.. does not match the first syntax because RegEx is by mặc định case-sensitive. But with the usage of the i flag, as seen in the second syntax, the string is as expected - replaced.

How to lớn use Split with Regular Expressions

split also uses RegEx. Which means you can split a string not just at substrings that match exact characters, but also patterns.

Here"s a quick look:

const regex = /d2a/;const str = "Hello54 How 64aare you";console.log(str.split(regex))// <"Hello54 How ", "are you">The string was split at 64a because that substring matches the regex specified.

lưu ý that the global flag - g - in split is irrelevant, unlượt thích the i flag và other flags. This is because split splits the string at the several points the regex matches.

Wrapping up

RegEx makes replaceing strings in JavaScript more effective, powerful, & fun.

You"re not only restricted to lớn exact characters but patterns and multiple replacements at once. In this article, we"ve sầu seen how they work together using a few examples.

Cheers to lớn RegEx ?

Dillion Megida

Frontover Web Engineer and Technical Writer. I love sầu teaching what I know. Javascript / ReactJS / NodeJS

Learn to lớn code for free.'s open source curriculum has helped more than 40,000 people get jobs as developers. Get started is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: khổng lồ help people learn khổng lồ code for free. We accomplish this by creating thousands of videos, articles, và interactive coding lessons - all freely available lớn the public. We also have sầu thousands of study groups around the world.

Donations lớn go toward our education initiatives, & help pay for servers, services, and staff.