How to Replace All Instances of a String with Another String

How do I replace all occurrences of a string in JavaScript?

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.js 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://jsben.ch/TZYzj

Conclusion:

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

Replace all occurrences of a substring in a string in C

For starters:

This line

strncpy(buffer, string, p-string);

not necessarily appends a 0-terminator to what had been copied to buffer.

The following line

strcat(buffer, replace);

however relies on buffer being 0-terminated.

As buffer had not been initialised and though the 0-terminator most likely misses the latter line may very well read beyond buffer's memory and with this invoke the infamous Undefined Behaviour.

How do I replace all instances of a string with another string?

The bug is in str.replace(start_pos, end_pos, to);

From the std::string doc at http://www.cplusplus.com/reference/string/string/replace/

string& replace ( size_t pos1, size_t n1,   const string& str );

You are using an end-position, while the function expects a length.

So change to:

while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // ...
}

Note: untested.

Replace multiple strings with multiple other strings

As an answer to:

looking for an up-to-date answer

If you are using "words" as in your current example, you might extend the answer of Ben McCormick using a non capture group and add word boundaries \b at the left and at the right to prevent partial matches.

\b(?:cathy|cat|catch)\b
  • \b A word boundary to prevent a partial match
  • (?: Non capture group
    • cathy|cat|catch match one of the alternatives
  • ) Close non capture group
  • \b A word boundary to prevent a partial match

Example for the original question:

let str = "I have a cat, a dog, and a goat.";
const mapObj = {
cat: "dog",
dog: "goat",
goat: "cat"
};
str = str.replace(/\b(?:cat|dog|goat)\b/gi, matched => mapObj[matched]);
console.log(str);

Replace all occurrences in a string by another string

You can use re.sub() to replace all occurrences of that pattern.

import re

s = "1 - 2 P_1(x) + 3 P_2(x) - 708.4250106547449 P_3(x)"

pattern = r' P_(\d+)\(x\)' # (\d+) captures the n in P_n
replace = r' * (x**\1)' # \1 uses the last captured n as a replacement

s_2 = re.sub(pattern, replace, s)
print(s_2)

Output:

1 - 2 * (x**1) + 3 * (x**2) - 708.4250106547449 * (x**3)

And with your full input:

s_3 = """487351.25373014854 - 152956.2387091797 P_1(x) +
14288.881396831219 P_2(x) - 708.4250106547449 P_3(x) +
22.029508388530736 P_4(x) - 0.46451906903633394 P_5(x) +
0.006931166409021728 P_6(x) - 7.493824771409185e-05 P_7(x) +
5.934862864562062e-07 P_8(x) - 3.442722590115344e-09 P_9(x) +
1.4457000568406937e-11 P_10(x) - 4.276159814629395e-14 P_11(x) +
8.446505496408776e-17 P_12(x) - 9.998295324026605e-20 P_13(x) +
5.362954837187194e-23 P_14(x)
"""

s_4 = re.sub(pattern, replace, s_3)
print(s_4)

Output:

487351.25373014854 - 152956.2387091797 * (x**1) +
14288.881396831219 * (x**2) - 708.4250106547449 * (x**3) +
22.029508388530736 * (x**4) - 0.46451906903633394 * (x**5) +
0.006931166409021728 * (x**6) - 7.493824771409185e-05 * (x**7) +
5.934862864562062e-07 * (x**8) - 3.442722590115344e-09 * (x**9) +
1.4457000568406937e-11 * (x**10) - 4.276159814629395e-14 * (x**11) +
8.446505496408776e-17 * (x**12) - 9.998295324026605e-20 * (x**13) +
5.362954837187194e-23 * (x**14)

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

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

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");

How to replace multiple substrings of a string?

Here is a short example that should do the trick with regular expressions:

import re

rep = {"condition1": "", "condition2": "text"} # define desired replacements here

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
#Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest versions
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

For example:

>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")
'() and --text--'

How to find and replace all occurrences of a substring in a string?

try the following

const std::string s = "*A";
const std::string t = "*A\n";

std::string::size_type n = 0;
while ( ( n = chartDataString.find( s, n ) ) != std::string::npos )
{
chartDataString.replace( n, s.size(), t );
n += t.size();
}


Related Topics



Leave a reply



Submit