Html replace all string

Replace All string JavaScript: replaceAll() Method

For a quick solution and learning of how to replace all a part of a string with another string in JavaScript, you can check the following code:

// replaceAll() method is used to replace all matches // in a string with another string. // 1. Replace "o" with "*" in "Hello World" var str = "Hello World"; var newStr = str.replaceAll("o", "*"); console.log(newStr); // "Hell* W*rld" // 2. Replace l and e with * (using regex) var str = "Hello World"; var newStr = str.replaceAll(/[le]/g, "*"); console.log(newStr); // H***o Wor*d // 3. call a function for each match var str = "Hello World"; var newStr = str.replaceAll(/o/g, function(match, index, originalText) < return "*" + match + "*"; >); console.log(newStr); // Hell*o* W*o*rld

replace All String JavaScript

To replace all occurrences of a match (word or random string) in a string use the replaceAll() method in JavaScript.

The replaceAll() method uses a string or regex (regular expression) to match a pattern within the string and replace it with another new string .

You can either directly specify the new string as the second parameter of the method or pass a function as the second parameter whose return value is used as a new string .

Читайте также:  Javascript duplicate object in array

Let’s see a basic example to start off, further in this section we will see more examples to explore the method and its arguments.

Example: Replacing all occurrences of «do» with «code»

// replace all string javascript var str = "to do or not to do"; // using string var newStr = str.replaceAll("do", "code"); console.log(newStr); // to code or not to code // Using regex var newStr = str.replaceAll(/do/g, "code"); console.log(newStr); // to code or not to code

In the above example, you can see whether you use a string or a regex to match the string the replaceAll method replaces all the occurrences of matching within the calling string.

replace string javascript example

Note : When using regex to find matching substring in the replaceAll() method using the /g flag with regex is necessary otherwise it will throw a TypeError («replaceAll must be called with a global RegExp»).

Syntax of replaceAll method

The syntax of replaceAll() method is as follows:

str.replaceAll(substr, new_string); str.replaceAll(regexp, new_string); str.replaceAll(substr, function); str.replaceAll(regexp, function);
  1. substr — The substring that is to be replaced by the new_string . It is not treated as a regular expression but just as a literal string.
  2. regexp — The regular expression used to find the match within the string and replace it with the new_string .
  3. new_string — The replacement string that replaces the matched pattern.
  4. function — The function as a second parameter that is invoked for every match of the pattern in the string. The method uses the return value of the function as a new string. The replacement function is discussed in detail below.

Note : The replaceAll method doesn’t change the original string it creates a new string by replacing the necessary substring and return it.

Replace All String Examples

Let’s see some example to replace strings or characters using the replaceAll method.

# Example 1: Matching by string

The example below replaces all the characters «d» with «g» using the string «d» as a matching string in the replaceAll method.

var str = "to do or not to do"; // replace "d" with "g" var newStr = str.replaceAll("d", "g"); console.log(newStr); // to go or not to go

# Example 2: Replacing all underscores and dashes with space

The following example uses a regular expression to find all underscores (_) and dashes (-) and replace all by space ( ) using the replaceAll method.

var str = "To-do_or_not_to-do"; // replace all underscores and dashes with space var newStr = str.replaceAll(/[_-]/g, " "); console.log(newStr); // To do or not to do

# Example 3: Channing replaceAll method

Suppose you have a string and you want to replace 2 more than 2 different matches from the string.

So the basic idea to do this would be to replace the matchings one by one and assign the return value every time to the original string, as shown in the example below.

var str = "To do or not to do."; str = str.replaceAll(/do/gi, 'code'); // replace all do with code str = str.replaceAll(/to/gi, 'love'); // replace all to with love console.log(str); // love code or not love code.

Instead of replacing and assigning return value one by one you can directly chain the replaceAll() method and do this in a single line of code.

let str = "To do or not to do."; // chaining the replaceAll() method str = str.replaceAll(/do/gi, "code").replaceAll(/to/gi, "love"); // replace all do with codeand replace all to with love console.log(str); // love code or not love code.

Non-global regex Error Throw

Using global flag ( /g ) is necessary with the replaceAll method otherwise it throws an error.

var str = "to do or not to do."; // no g flag str.replaceAll(/do/, "Sleep"); // Throw Error

The above code throws an error, so added a global flag to the regex in the example below a this works.

const str = "to do or not to do."; // always use g flag with replaceAll Methods let newStr = str.replaceAll(/do/g, "Sleep"); console.log(newStr);

Using a replacement function

In the above examples, you have seen and used a direct string to replace the matching substring in the replaceAll method. But you can use a replacement function as a second parameter to the method whose return value is used as a new string to replace the matching substrings.

Here is how you can add a replacement function to the method.

str.replaceAll(substr, replacement_function); str.replaceAll(regex, replacement_function);

The replacement function is invoked after a match has been performed within the string. If there are multiple matches then the method the replacement function will be invoked for each match.

The return value of the replacement function is used as a new string to replace the matching string, which can be the same or different for each match.

const str = "to do or not to do."; const pattern = /do/g; function replacer() < return "Sleep"; >console.log(str.replaceAll(pattern, replacer)); // to Sleep or not to Sleep.

In the above example, the replacement function is invoked every time a match is performed and uses the return value as a new string to replace all the matches.

Let’s now understand the replacer function in detail.

Syntax of replacement function

function replacer(match, p1, p2, . offset, string)

Following are the arguments of the replacement function:

Arguments Description
match This is the part of the string that matches the pattern
p1, p2, . The string is found by parenthesized capturing group in the string. This means p1 will be the first capture of capturing group, p2 will be the second, and so on.
offset This is the index value of matched substring or capturing group.
string The string that calls the method

The following example shows the matches and the replaced value for the match using the replacement function.

Showing match using replacement function

const str = "to do or not to do."; const pattern = /do/g; function replacer(match) < return `($) => Sleep`; > console.log(str.replaceAll(pattern, replacer)); // to Sleep or not to Sleep.

The example below shows the captures of the capturing group by the regex used in the method.

const str = "to do or not to do."; const pattern = /d(o)/g; function replacer(match, p1) < return `($) => Sleep \n(capturing $)\n`; > console.log(str.replaceAll(pattern, replacer));

The example below shows the captures offset of the capturing group within the string.

const str = "to do or not to do."; const pattern = /d(o)/g; function replacer(match, p1, offset) < return `($) => Sleep \n(capturing $) at index $\n`; > console.log(str.replaceAll(pattern, replacer));

The example below uses all the parameters of the replacement function.

const str = "to do or not to do."; const pattern = /d(o)/g; function replacer(match, p1, offset, string) < return `($) => Sleep \n(capturing $) at index $ in ($)\n`; > console.log(str.replaceAll(pattern, replacer));

Array Function As Replacement Function

You can use also the array function as a replacement function for the replaceAll() method both anonymous function or named function.

const str = "to do or not to do."; const pattern = /d(o)/g; const newStr = str.replaceAll(pattern, (match, p1, offset, string) => < return `($) => Sleep \n(capturing $) at index $ in ($)\n` >) console.log(newStr);

Alternate method : Using Split and Join Method To Replace String

You would be familiar with the split and join method of the array. The split method splits any string and put it in the array when it finds a certain substring init, while the join method joins the members of an array into a string by adding a string between 2 members of the array.

We can use this combined to create the same effect as the replaceAll method. Split your string at the matching string and join the array by passing the new string as a separator in the join method. See the example below.

const str = "to do or not to do."; const subStr = "do"; const replaceBy = "Sleep"; const newStr = str.split(subStr).join(replaceBy); console.log(newStr);

The above example split the string using the split method when it finds «do» in the string and join them using «Sleep» as a separator in the join method.

Conclusion

To replace all the occurrences of a string or any pattern use replaceAll() method in javascript. We have seen this method in detail in this guide.

Источник

String.prototype.replaceAll()

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

Try it

Syntax

replaceAll(pattern, replacement) 

Parameters

Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn’t have the Symbol.replace method will be coerced to a string.

If pattern is a regex, then it must have the global ( g ) flag set, or a TypeError is thrown.

Can be a string or a function. The replacement has the same semantics as that of String.prototype.replace() .

Return value

A new string, with all matches of a pattern replaced by a replacement.

Exceptions

Thrown if the pattern is a regex that does not have the global ( g ) flag set (its flags property does not contain «g» ).

Description

This method does not mutate the string value it’s called on. It returns a new string.

Unlike replace() , this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the RegExp() constructor without escaping special characters may unintentionally change its semantics.

function unsafeRedactName(text, name)  return text.replace(new RegExp(name, "g"), "[REDACTED]"); > function safeRedactName(text, name)  return text.replaceAll(name, "[REDACTED]"); > const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." 

If pattern is an object with a Symbol.replace method (including RegExp objects), that method is called with the target string and replacement as arguments. Its return value becomes the return value of replaceAll() . In this case the behavior of replaceAll() is entirely encoded by the @@replace method, and therefore will have the same result as replace() (apart from the extra input validation that the regex is global).

If the pattern is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to split() behavior.

For more information about how regex properties (especially the sticky flag) interact with replaceAll() , see RegExp.prototype[@@replace]() .

Источник

Оцените статью