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.
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 in a string
Use the global flag.
str.replace(/\n/g, '<br />');
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.
Replace all instances of character in string in typescript?
Your second example is the closest. The first problem is your variable name, new
, which happens to be one of JavaScript's reserved keywords (and is instead used to construct objects, like new RegExp
or new Set
). This means that your program will throw a Syntax Error.
Also, since the dot (.
) is a special character inside regex grammar, you should escape it as \.
. Otherwise you would end up with result == "xxxxxxxxxxxxxxxxxx"
, which is undesirable.
let email = "my.email@email.com"
let re = /\./gi;let result = email.replace(re, "x");
console.log(result)
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 all occurrences of a string inside tags using regex in java
We can try using a formal regex pattern matcher here. Match on the pattern <abc~a>(.*?)<abc~a>
, and for each match append the tag with src
replaced by abc
. Here is a sample code:
String input = "Here is a src <abc~a>I am an src customer<abc~b> also another src here.";
Pattern p = Pattern.compile("<abc~a>(.*?)<abc~b>");
Matcher m = p.matcher(input);
StringBuffer buffer = new StringBuffer();
while(m.find()) {
String replace = "<abc~a>" + m.group(1).replaceAll("\\bsrc\\b", "abc") + "<abc~b>";
m.appendReplacement(buffer, replace);
}
m.appendTail(buffer);
System.out.println(buffer.toString());
This prints:
Here is a src <abc~a>I am an abc customer<abc~b> also another src here.
Note that in many other languages we could have used a regex callback function. But core Java does not support this functionality, so we have to iterate over the entire input.
Why doesn't replace () change all occurrences?
It did make all replacements (that's what .replace()
does in Python unless specified otherwise), but some of these replacements inadvertently introduced new instances of GAGA. Take the beginning of your string:
TGCGAGAA
There's GAGA at indices 3-6. If you replace that with AGAG, you get
TGCAGAGA
So the last G from that AGAG, together with the subsequent A that was already there before, forms a new GAGA.
Replace all except the first occurrence of a substring in Python?
With additional "reversed" substitution step:
s = "SELECT sdfdsf SELECT sdrrr SELECT 5445ff"
res = s.replace("SELECT", "@@@SELECT").replace("@@@SELECT", "SELECT", 1)
print(res)
The output:
SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff
A more sophisticated, but ensuring target word boundaries, could be as below:
import re
def make_replacer():
rpl = ''
def inner(m):
nonlocal rpl
res = rpl + m.group()
rpl = '@@@'
return res
return inner
s = "SELECT sdfdsf SELECT sdrrr SELECT 5445ff"
res = re.sub(r'\bSELECT\b', make_replacer(), s)
print(res) # SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff
How to replace all occurrences of a string except the first one in JavaScript?
You can pass a function to String#replace, where you can specify to omit replacing the first occurrence. Also make your first parameter of replace a regex to match all occurrences.
Demo
let str = 'hello world hello world hello world hello', i = 0; str = str.replace(/world/g, m => !i++ ? m : '');console.log(str);
Related Topics
Create a File Using JavaScript in Chrome on Client Side
Aggregation Filter After $Lookup
How to Ignore User's Time Zone and Force Date() Use Specific Time Zone
Node.Js Variable Declaration and Scope
How to Completely Disable Any Mouse Click
Moment.Js Transform to Date Object
How to Store a Global Value (Not Necessarily a Global Variable) in Jquery
Ajax Post and Plus Sign ( + ) -- How to Encode
Promise Constructor with Reject Call VS Throwing Error
How to Detect Right Mouse Click + Paste Using JavaScript
Selecting Multiple Classes with Jquery
How to Format a Date in Mm/Dd/Yyyy Hh:Mm:Ss Format in JavaScript
Jqgrid Gridunload/ Griddestroy
How to Make a Div Element Editable (Like a Textarea When I Click It)
How to Call a Parent Method from Child Class in JavaScript
Assign Variable in If Condition Statement, Good Practice or Not