Document

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.

Читайте также:  How to change my php version

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]() .

Источник

JavaScript String replace()

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

Note

See Also:

Syntax

Parameters

Parameter Description
searchValue Required.
The value, or regular expression, to search for.
newValue Required.
The new value (to replace with).

Return Value

More Examples

A global, case-insensitive replacement:

A function to return the replacement text:

let text = «Mr Blue has a blue house and a blue car»;
let result = text.replace(/blue|house|car/gi, function (x) return x.toUpperCase();
>);

Browser Support

replace() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

How to Replace Content in Javascript

In this tutorial, you will learn how to replace content in javascript. The content can be in the form of plain text or HTML. For instance, a div can have other elements as its child and a paragraph element can have only text.

Most of the elements have innerText and innerHTML properties. The innerText property is best suited in case you want to replace text content of an element such as paragraph element. On the other hand, the innerHTML property is best suited when you want to replace HTML content of an element such as div element. We are going to see both of them in action.

In the following example, we have 2 buttons, one to replace text content and another to replace HTML content. Please have a look over the code example and steps given below.

  • We have a few elements in the HTML file ( div , button , and p ).
  • The first div element with a class of container is just a wrapper for the rest of the elements.
  • The first button element has “Text” and the second button element has “HTML” as inner text. Both of them are wrapped with a div element.
  • We have another div element with a class of content and it has a paragraph element as its child.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
          
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Consequatur, odio pariatur quam nostrum eos deleniti maiores rerum neque obcaecati similique est quae illo nihil fugiat enim eligendi ullam possimus labore?

.container,#content < display: flex; flex-direction: column; align-items: center; justify-content: center; >#content < padding: 10px; margin-top: 10px; border: 1px solid black; width: 50%; min-height: 100px; >button

  • We have selected both the button elements and content div element by id and paragraph element by tag name using the document.querySelector() method and stored them in btnText , btnHtml , content , and paragraph variables respectively.
  • We have attached the click event listener to both the button elements.
  • Inside the event handler function of the first button btnText , we are changing the text content of the paragraph element using the innerText property.
  • Inside the event handler function of the second button btnHtml , we are changing the HTML content of the div element using the innerHTML property.
let btnText = document.querySelector('#btnText'); let btnHtml = document.querySelector('#btnHtml'); let content = document.querySelector('#content'); let paragraph = document.querySelector('p'); btnText.addEventListener('click', () => < paragraph.innerText = 'Hello World'; >); btnHtml.addEventListener('click', () => < content.innerHTML = '

Hello World

'; >);

Источник

JavaScript Replace – How to Replace a String or Substring in JS

Joel Olawanle

Joel Olawanle

JavaScript Replace – How to Replace a String or Substring in JS

When working with JavaScript, you might need to replace a string or substring with a new one.

For example, you might want to replace a certain string (like «color” — American English) or substring in a larger text or document with a different string (“colour” — British English). You may also want to replace certain characters or symbols from a string to make sure your program will work.

In this article, you will learn how to use JavaScript’s replace() method to replace a string or substring.

How to Replace a String or Substring with the replace() Method

In JavaScript, you can use the replace() method to replace a string or substring in a string. The replace() method returns a new string with the replacement. The replace() method takes two arguments:

  1. The first argument is the string or regular expression to be replaced.
  2. The second argument is the string that will replace the matched string or regular expression.
// Syntax string.replace(searchValue, replaceValue) 

In the syntax above, string is the string you want to perform the replacement on. The searchValue parameter is either a string or a regular expression that you want to search for in the string . The replaceValue parameter is the string that will replace the searchValue .

Note: Only the first instance will be replaced. If you want to replace all instances, you will have to use the replaceAll() method.

JavaScript String replace() Examples

Suppose you have a string that uses “color” which is America English and want to change “color” to “colour”, the British English form. Here is an example of how you can do this:

let originalString = "The color of the sky changes throughout the day."; let newString = originalString.replace("color", "colour"); console.log(newString); 

This will replace “color” in the string and return a new string assigned to the variable newString .

"The colour of the sky changes throughout the day." 

In a situation where you have more than one occurence of such substring, you can use the replaceAll method:

let originalString = "The color of the sky changes throughout the day, and sometimes the color of the clouds creates a beautiful contrast. The color of a flower can indicate its species, and the color of clothing can affect someone's mood."; let newString = originalString.replaceAll("color", "colour"); console.log(newString); 

This will replace all instances of “color” in the string and return a new string assigned to the variable newString .

"The colour of the sky changes throughout the day, and sometimes the colour of the clouds creates a beautiful contrast. The colour of a flower can indicate its species, and the colour of clothing can affect someone's mood." 

How to Replace Multiple Strings and Substring with the replace() Method

Sometimes you may want to change more than one string or substring in one string variable. For example, in the text below, you may want to change “color” to “colour” and “JS” to “JavaScript”.

let originalString = "Using JS, you can change the color of a webpage's background, text, and elements." 

You can do that by chaining as many replace() methods as needed:

let originalString = "Using JS, you can change the color of a webpage's background, text, and elements."; let newString = originalString .replace("color", "colour") .replace("JS", "JavaScript"); console.log(newString); 

This will return a new string with both instances replaced:

"Using JavaScript, you can change the colour of a webpage's background, text, and elements." 

Also, you may want to replace multiple strings or substrings with just one string. For example, you may want to replace where “quick”, “fox”, and “brown” with one string — “hello”:

let originalString = "The quick brown fox jumps over the lazy dog."; let newString = originalString.replace(/quick|brown|fox/g, "hello"); console.log(newString); // Output: "The hello hello hello jumps over the lazy dog." 

How to Use replace() with Regular Expressions

In JavaScript, you can use the replace() method with regular expressions to replace strings and substrings with more flexibility and power. For example:

let originalString = "Today is a sunny day. I love sunny days!"; let newString = originalString.replace(/sunny/g, "cloudy"); console.log(newString); // Output: "Today is a cloudy day. I love cloudy days!" 

In this example, the regular expression /sunny/g matches all occurrences of the substring «sunny» in the originalString . The g flag specifies that all matches should be replaced. The replacement string «cloudy» replaces all matched substrings, resulting in the newString «Today is a cloudy day. I love cloudy days!»

Regular expressions can also be used to match patterns or groups of characters. For example:

let originalString = "My phone number is (123) 456-7890"; let newString = originalString.replace(/\D/g, ""); console.log(newString); // Output: "1234567890" 

In this example above, the regular expression /\D/g matches all non-digit characters in the originalString . The \D character class matches any character that is not a digit. The g flag specifies that all matches should be replaced.

Case-sensitive Replacement with Regular Expressions

Regular expressions make it possible for you to perform advanced search and replace operations. For example, using the i flag, you can replace only strings and substrings whose case matches perfectly:

const originalString = "I love JavaScript and javascript loves me"; const newString = originalString.replace(/JavaScript/i, "Python"); console.log(newString); // Output: "I love Python and javascript loves me" 

In this example, the replace() method replaces the first occurrence of the word «JavaScript» with «Python» in the originalString variable. The /i flag is used to perform a case-insensitive search.

Wrapping Up

In this article, you have learned how to replace a string or substring in JavaScript with the replace() method and the various instances in which the replace() method can work.

Hopefully, this article has given you a better understanding of how to use the replace() and replaceAll() method in JavaScript.

You can access over 188 of my articles by visiting my website. You can also use the search field to see if I’ve written a specific article.

Источник

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