HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Fastest method to replace all instances of a character in a string

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
replaceinstancesmethodcharacterstringallfastest

Problem

What is the fastest way to replace all instances of a string/character in a string in JavaScript? A while, a for-loop, a regular expression?

Solution

The easiest would be to use a regular expression with g flag to replace all instances:

str.replace(/foo/g, "bar")


This will replace all occurrences of foo with bar in the string str. If you just have a string, you can convert it to a RegExp object like this:

var pattern = "foobar",
    re = new RegExp(pattern, "g");

Code Snippets

str.replace(/foo/g, "bar")
var pattern = "foobar",
    re = new RegExp(pattern, "g");

Context

Stack Overflow Q#2116558, score: 1320

Revisions (0)

No revisions yet.