JavaScript String replace() Method

You are Here:

JavaScript String replace() Method

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

Note: 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.

Using String

Note: If pattern is a string, only the first occurrence will be replaced.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var str = "Tiger is king of the jungle"; var result = str.replace("Tiger", "Lion"); document.write(result); </script> </body> </html>

Syntax

str.replace(find, replaceWith)

Parameter Values

ValueTypeExplanation
findRequiredTo find the characters in your string which is to be replaced.
Use string or regexp to find the characters to be replaced.
replaceWithRequiredThe value to replace the find values.
Use string or function to replace the 'find value' in the string.

Return Value

ValueExplanation
stringReturns a new string, where specific or all matches of a pattern replaced by a replacement.

Using RegExp

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var str = "He is good and he likes her."; var result = str.replace(/he/g, "she"); document.write(result); </script> </body> </html>

Using Function for Replacement

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var str = "ai means Artificial intelligence"; var result = str.replace("ai", function (x) { return x.toUpperCase(); }); document.write(result); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author