Skip to content
Fix Code Error

How to replace all occurrences of a string in Javascript?

March 13, 2021 by Code Error
Posted By: Anonymous

I have this string in my Javascript code:

"Test abc test test abc test test test abc test test abc"

Doing:

str = str.replace('abc', '');

seems to only remove the first occurrence of abc in the string above.

How can I replace all occurrences of it?

Solution

Update: In the latest versions of most popular browsers, you can use replaceAll
as shown here:

let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"

But check Can I use or another compatibility table first to make sure the browsers you’re targeting have added support for it first.


For Node and compatibility with older/non-current browsers:

Note: Don’t use the following solution in performance critical code.

As an alternative to regular expressions for a simple literal string, you could use

str = "Test abc test test abc test...".split("abc").join("");

The general pattern is

str.split(search).join(replacement)

This used to be faster in some cases than using replaceAll and a regular expression, but that doesn’t seem to be the case anymore in modern browsers.

Benchmark: https://jsperf.com/replace-all-vs-split-join

Conclusion: If you have a performance critical use case (e.g processing hundreds of strings), use the Regexp method. But for most typical use cases, this is well worth not having to worry about special characters.

Answered By: Anonymous

Related Articles

  • How to properly do JSON API GET requests and assign…
  • How to represent arrays within ember-data models?
  • Rails wrong number of arguments error when…
  • How to parse JSON with XE2 dbxJSON
  • Azure Availability Zone ARM Config
  • The 'compilation' argument must be an instance of…
  • How to format a phone number in a textfield
  • 'block in draw' rails 6 routes
  • mongodb group values by multiple fields
  • data.table vs dplyr: can one do something well the…
  • Search match multiple values in single field in…
  • Event Snippet for Google only shows one event while…
  • Avoid creating new session on each axios request laravel
  • distinct unordered dynamic column in kusto
  • Why does this Azure Resource Manager Template fail…
  • loop and eliminate unwanted lines with beautiful soup
  • How to filter a RecyclerView with a SearchView
  • NullpointerException error while working with…
  • Vue JS – Using v-if with components
  • Most effective way to parse JSON Objects
  • problem with client server unix domain stream…
  • How do I limit the number of digits from 6 to 4 in…
  • Azure CLI - az deployment group create -…
  • Octave using 'for' statement to show two animations…
  • Smart way to truncate long strings
  • Does moment.js allow me to derive a timezone…
  • Validate that a string is a positive integer
  • How to traverse the complex nested Json in C# and…
  • Angular 12 - Generating browser application bundles…
  • Siemens LOGO! PLC data in the wrong order
  • How do we split words from a html file using string…
  • How to properly update the library parts
  • Python is not calling fucntions properly
  • Python JSON TypeError : list indices must be…
  • C# Get YouTube videoId from Json
  • Python scrape JS data
  • ./components/Avatar.tsx Error: Cannot find module…
  • What does do?
  • How to use Servlets and Ajax?
  • How do I tell Maven to use the latest version of a…
  • Can't upload files with Apollo-client GraphQL in…
  • How to build correlation matrix plot using specified…
  • How to print a string at a fixed width?
  • How do I remove single children in a tree?
  • How to forcefully set IE's Compatibility Mode off…
  • Homebrew install specific version of formula?
  • error NG6002: Appears in the NgModule.imports of…
  • Sorting A Table With Tabs & Javascript
  • Python - Read JSON - TypeError: string indices must…
  • Need constraints for y position or height when…
  • Posting array of objects to REST API with ReactJS
  • One to many relationship in two JSON arrays, lookup…
  • Using Auto Layout in UITableView for dynamic cell…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • TypeError: players.map is not a function
  • How to check if a string contains text from an array…
  • Scraping text after a span in with Regex (and Requests)
  • Error Stack Overflow when trying to hide buttons in…
  • Getting a "TypeError" when trying to validate a form
  • Combining pyOSC with pyQT5 / Threading?
  • How do I install Java on Mac OSX allowing version switching?
  • Azure Sql : Unable to Replace HTML String
  • Sort table rows In Bootstrap
  • Compare 2nd and 3rd field of CSV file for each row…
  • C++ Need help sorting a 2D string array
  • Blazor Can't Update UI
  • Identifying and solving…
  • Latest jQuery version on Google's CDN
  • how to turn a recursive algorithms into an iterative one
  • Issues trying to install sylius/product-bundle to my…
  • Can't understand the difference between declaring a…
  • Function runs into an error after successfully…
  • Video Poker How to make the combinations?
  • SQL query return data from multiple tables
  • Split JSON python string to pass to function
  • I want to create a SQLite database like in the…
  • Javascript filtering a nested array to exclude…
  • For-each over an array in JavaScript
  • Java replace all square brackets in a string
  • What is your most productive shortcut with Vim?
  • Programmatically generate url from path and params
  • Dynamically changing url in Backbone
  • How does String substring work in Swift
  • state data can not be set using useState in reactjs
  • How can i use `parse = T` and functions like round…
  • How to query Json field so the keys are the column…
  • How do I keep only the first map and when the game…
  • How to blur the background after click on the button…
  • Js Calculation based on radio button, and some problems
  • How do I get currency exchange rates via an API such…
  • React function keeps refreshing page causing huge…
  • What's the difference between eval, exec, and compile?
  • Why is my Shopify App built with Next.js (React) so…
  • Remove Text from the edit text when edit text is focused
  • How to determine the current iPhone/device model?
  • python pandas - add unique Ids in column from master…
  • Fragment Not Showing in the Activity
  • What is an optional value in Swift?
  • Reversing a string in C
  • Vega-lite data transformation to un-nest objects

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Regular expression to match a line that doesn’t contain a word

Next Post:

How do I clone a specific Git branch?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error