How to Replace All Occurrences of a String in JavaScript

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

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

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.

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

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

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.

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

replace all occurrences in a string

Use the global flag.

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

JS replacing all occurrences of string using variable

The RegExp constructor takes a string and creates a regular expression out of it.

function name(str,replaceWhat,replaceTo){
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}

If replaceWhat might contain characters that are special in regular expressions, you can do:

function name(str,replaceWhat,replaceTo){
replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}

See Is there a RegExp.escape function in Javascript?

How to replace all occurrences inside an object?

map is what you're looking for

const users = [{
"userid": "1",
"fornonmods": "<div id=\"user1\" data-login=\"\" data-status=\"online\" class=\"item\">",
"formods": "<div id=\"user1\" data-login=\"\" data-status=\"online\" class=\"item\">"
}, {
"userid": "19917",
"fornonmods": "<div id=\"user19917\" data-login=\"kBr4pelyDy4yKVmiAAAD\" data-status=\"online\" class=\"item\">",
"formods": "<div id=\"user19917\" data-login=\"kBr4pelyDy4yKVmiAAAD\" data-status=\"online\" class=\"item\">"
}];

const id = "kBr4pelyDy4yKVmiAAAD";

const res = users.map(x => {
const container = {};

container.userid = x.userid,
container.fornonmods = x.fornonmods.replace(`data-login=\"${id}\" data-status=\"online\"`, `data-login=\"${id}\" data-status=\"gagged\"`);
container.formods = x.formods.replace(`data-login=\"${id}\" data-status=\"online\"`, `data-login=\"${id}\" data-status=\"gagged\"`);

return container;
});

console.log(res);

JavaScript - Replace all commas in a string

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

var myStr = 'this,is,a,test';var newStr = myStr.replace(/,/g, '-');
console.log( newStr ); // "this-is-a-test"

Replace All Occurrences in a String with JavaScript

In order to replace all occurrences you can use regular expression with g (i.e. global) flag:

"111".replace(/1/g, "2");

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

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.



Related Topics



Leave a reply



Submit