Learn JavaScript
  • Introduction
  • Basics
    • Comments
    • Variables
    • Types
    • Equality
  • Numbers
    • Math
    • Basic Operators
    • Advanced Operators
  • Strings
    • Creation
    • Replace
    • Length
    • Concatenation
  • Conditional Logic
    • If
    • Else
    • Switch
    • Comparators
    • Concatenate
  • Arrays
    • Unshift
    • Map
    • Spread
    • Shift
    • Pop
    • Join
    • Length
    • Push
    • For Each
    • Sort
    • Indices
  • Loops
    • For
    • While
    • Do...While
  • Functions
    • Higher Order Functions
  • Objects
    • Properties
    • Mutable
    • Reference
    • Prototype
    • Delete
    • Enumeration
    • Global footprint
  • Linked List
    • Add
    • Pop
    • Prepend
    • Shift
  • Browser Object Model (BOM)
    • Window
    • Popup
    • Screen
    • Navigator
    • Cookies
    • History
    • Location
  • Date and Time
  • JSON
  • Error Handling
    • try...catch...finally
  • Events
  • Regular Expression
  • Modules
  • Debugging
  • Classes
    • Static
    • Inheritance
    • Access Modifiers
  • Promise, async/await
    • Async/Await
  • Miscellaneous
    • Hoisting
    • Currying
    • Polyfills and Transpilers
  • Exercises
    • Console
    • Multiplication
    • User Input Variables
    • Constants
    • Concatenation
    • Functions
    • Conditional Statements
    • Objects
    • FizzBuzz Problem
    • Get the Titles!
Powered by GitBook
On this page

Was this helpful?

  1. Strings

Replace

PreviousCreationNextLength

Last updated 2 years ago

Was this helpful?

The replace method allows us to replace a character, word, or sentence with a string. For example.

let str = "Hello World!";
let new_str = str.replace("Hello", "Hi");

console.log(new_str);

// Result: Hi World!

To replace a value on all instances of a with a g modifier is set.

It searches for a string for a value or a regular expression and returns a new string with the value(s) replaced. It doesn't change the original string. Let's see the global case-insensitive replacement example.

let text = "Mr Blue has a blue house and a blue car";
let result = text.replace(/blue/gi, "red"); 

console.log(result); 
//Result: Mr red has a red house and a red car 

regular expression