惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Securelist
C
CERT Recently Published Vulnerability Notes
Forbes - Security
Forbes - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 最新话题
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
SecWiki News
SecWiki News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The Last Watchdog
The Last Watchdog
S
Schneier on Security
T
Troy Hunt's Blog
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Schneier on Security
Schneier on Security
P
Privacy & Cybersecurity Law Blog
T
Tor Project blog
T
Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
A
Arctic Wolf
S
Secure Thoughts
P
Proofpoint News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Security Latest
Security Latest
Scott Helme
Scott Helme
Security Archives - TechRepublic
Security Archives - TechRepublic
Latest news
Latest news
PCI Perspectives
PCI Perspectives
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
G
GRAHAM CLULEY
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
Project Zero
Project Zero
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
Webroot Blog
Webroot Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
大猫的无限游戏
大猫的无限游戏
T
Tenable Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Hacker News: Front Page
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
3 Ways To Replace All String Occurrences in JavaScript
Dmitri Pavlutin · 2019-12-24 · via Dmitri Pavlutin Blog

In this post, you'll learn how to replace all string occurrences in JavaScript by splitting and joining a string, string.replace() combined with a global regular expression, and string.replaceAll().

Table of Contents

  • 1. Splitting and joining an array
  • 2. replace() with a global regular expression
    • 2.1 Regular expression from a string
    • 2.2 replace() with a string
  • 3. replaceAll() method
    • 3.1 The difference between replaceAll() and replace()
  • 4. Key takeaway

1. Splitting and joining an array

If you google how to "replace all string occurrences in JavaScript", the first approach you are likely to find is to use an intermediate array.

Here's how it works:

  1. Split the string into pieces by the search string:


const pieces = string.split(search);


  1. Then join the pieces putting the replace string in between:


const resultingString = pieces.join(replace);


For example, let's replace all spaces ' ' with hyphens '-' in 'duck duck go' string:


const search = ' ';

const replaceWith = '-';

const result = 'duck duck go'.split(search).join(replaceWith);

console.log(result); // => 'duck-duck-go'


Open the demo.

'duck duck go'.split(' ') splits the string into pieces: ['duck', 'duck', 'go'].

Then the pieces ['duck', 'duck', 'go'].join('-') are joined by inserting '-' in between them, which results in the string 'duck-duck-go'.

Here's a generalized helper function that uses splitting and joining approach:


function replaceAll(string, search, replace) {

return string.split(search).join(replace);

}

console.log(replaceAll('abba', 'a', 'i')); // => 'ibbi'

console.log(replaceAll('go go go!', 'go', 'move')); // => 'move move move!'

console.log(replaceAll('oops', 'z', 'y')); // => 'oops'


Open the demo.

This approach requires transforming the string into an array, and then back into a string. Let's continue looking for better alternatives.

2. replace() with a global regular expression

The string method string.replace(regExpSearch, replaceWith) searches and replaces the occurrences of the regular expression regExpSearch with replaceWith string.

To make the method replace() replace all occurrences of the pattern - you have to enable the global flag on the regular expression:

  1. Append g to the end of regular expression literal: /search/g
  2. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')

Let's replace all occurrences of ' ' with '-':


const searchRegExp = /\s/g;

const replaceWith = '-';

const result = 'duck duck go'.replace(searchRegExp, replaceWith);

console.log(result); // => 'duck-duck-go'


Open the demo.

The regular expression literal /\s/g (note the g global flag) matches the space ' '.

'duck duck go'.replace(/\s/g, '-') replaces all matches of /\s/g with '-', which results in 'duck-duck-go'.

You can easily make case insensitive replaces by adding i flag to the regular expression:


const searchRegExp = /duck/gi;

const replaceWith = 'goose';

const result = 'DUCK Duck go'.replace(searchRegExp, replaceWith);

result; // => 'goose goose go'


The regular expression /duck/gi performs a global case-insensitive search (note i and g flags). /duck/gi matches 'DUCK', as well as 'Duck'.

Invoking 'DUCK Duck go'.replace(/duck/gi, 'goose') replaces all matches of /duck/gi substrings with 'goose'.

2.1 Regular expression from a string

When the regular expression is created from a string, you have to escape the characters - [ ] / { } ( ) * + ? . \ ^ $ | because they have special meaning within the regular expression.

Because of that, the special characters are a problem when you'd like to make replace all operation. Here's an example:


const search = '+';

const searchRegExp = new RegExp(search, 'g'); // Throws SyntaxError

const replaceWith = '-';

const result = '5+2+1'.replace(searchRegExp, replaceWith);


Open the demo.

The above snippet tries to transform the search string '+' into a regular expression. But '+' is an invalid regular expression, thus SyntaxError: Invalid regular expression: /+/ is thrown.

Escaping the character '\\+' solves the problem. Try the fixed demo.

2.2 replace() with a string

If the first argument search of string.replace(search, replaceWith) is a string, then the method replaces only the first occurrence of search:


const search = ' ';

const replace = '-';

const result = 'duck duck go'.replace(search, replace);

console.log(result); // => 'duck-duck go'


Open the demo.

'duck duck go'.replace(' ', '-') replaces only the first appearance of a space.

3. replaceAll() method

Finally, the method string.replaceAll(search, replaceWith) replaces all appearances of search string with replaceWith.

Let's replace all occurrences of ' ' with '-':


const search = ' ';

const replaceWith = '-';

const result = 'duck duck go'.replaceAll(search, replaceWith);

console.log(result); // => 'duck-duck-go'


Open the demo.

'duck duck go'.replaceAll(' ', '-') replaces all occurrences of ' ' string with '-'.

string.replaceAll(search, replaceWith) is the best way to replace all string occurrences in a string

Note that browser support for this method is currently limited, and you might require a polyfill.

3.1 The difference between replaceAll() and replace()

The string methods replaceAll(search, replaceWith) and replace(search, replaceWith) work the same way, except 2 things:

  1. If search argument is a string, replaceAll() replaces all occurrences of search with replaceWith, while replace() replaces only the first occurence
  2. If search argument is a non-global regular expression, then replaceAll() throws a TypeError exception.

4. Key takeaway

The first approach to replacing all occurrences is to split the string into chunks by the search string and then join back the string, placing the replace string between the chunks: string.split(search).join(replaceWith). This approach works, but it's hacky.

Another approach is to use string.replace(/SEARCH/g, replaceWith) with a regular expression having the global flag enabled.

Unfortunately, you cannot easily generate regular expressions from a string at runtime, because the special characters of regular expressions have to be escaped.

Finally, the string method string.replaceAll(search, replaceWith) replaces all string occurrences.

I recommend using string.replaceAll() to replace strings.

What other ways to replace all string occurrences do you know? Please share in a comment below!