Fastest method to replace all instances of a character in a string [duplicate]
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 character in string?
std::string
doesn't contain such function but you could use stand-alone replace
function from algorithm
header.
#include <algorithm>
#include <string>
void some_func() {
std::string s = "example string";
std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}
replace all occurrences in a string [duplicate]
Use the global flag.
str.replace(/\n/g, '<br />');
Replace all occurrences of a character in a string after the first one
With a bit of regex:
string s = "abc; abc bla bla ;;;;; bla bla";
var regex = new Regex("(?<!^[^;]*);");
var result = regex.Replace(s,":");
Console.WriteLine(result);
Live example: http://rextester.com/ORZU81353
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.
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)
replace all occurrences of a character in a string in java? [duplicate]
You want to escape the .
. Otherwise, it can match anything.
Try s.replaceAll("\\.", " ")
instead.
Replace all occurrences of a character between two strings
You may use
Find What: (?:\G(?!^)|string1)(?:(?!string1|string2).)*?\K\h(?=.*string2)
Replace With: _
See the regex demo.
NOTE:
- If you need to only match regular spaces, replace
\h
with a regular space - A more appropriate check for the end of the previous successful match is
\G(?!^(?<![\s\S]))
, but if your expected matches are on a single line, you might go on using\G(?!^)
.
Details
(?:\G(?!^)|string1)
- either the end of the previous match (but not start of a line) orstring1
(?:(?!string1|string2).)*?
- any char, 0 or more times, but as few as possible, that is not startingstring1
orstring2
char sequence\K
- discard the text matched so far\h
- any horizontal whitespace(?=.*string2)
- there must be astring2
after any 0 or more chars other than line break chars as many as possible immediately to the right of the current location.
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
What Is the Copy-And-Swap Idiom
What Are the Differences Between a Pointer Variable and a Reference Variable
What Is a Smart Pointer and When Should I Use One
Where Do I Find the Current C or C++ Standard Documents
Difference Between Const Int*, Const Int * Const, and Int Const *
How to Set, Clear, and Toggle a Single Bit
When Should Static_Cast, Dynamic_Cast, Const_Cast, and Reinterpret_Cast Be Used
When and Why Will a Compiler Initialise Memory to 0Xcd, 0Xdd, etc. on Malloc/Free/New/Delete
What Uses Are There For "Placement New"
System("Pause"); - Why Is It Wrong
What Is the Bit Size of Long on 64-Bit Windows
How Does the Compilation/Linking Process Work
What Happens If I Define a 0-Size Array in C/C++