.replace(old,new)

Description

The .replace() method replaces occurrences of text in a string. It supports both literal string replacement and regular expression patterns.

Parameters

  • old: The text to replace. Can be either:

    • A literal string to match exactly

    • A regex pattern in the format "/pattern/flags"

  • new: The text to replace matches with

Usage

Basic String Replacement

text = "hello world"
result = text.replace("hello", "hi")
// returns "hi world"

Regular Expression Replacement

// Replace all occurrences (global flag)
text = "hello hello hello"
result = text.replace("/hello/g", "hi")
// returns "hi hi hi"

// Case insensitive match
text = "Hello HELLO hello"
result = text.replace("/hello/gi", "hi")
// returns "hi hi hi"

Regex Flags

When using regex patterns, you can add flags after the closing slash:

  • g - global (replace all matches)

  • i - case insensitive

  • m - multiline

Examples

// Basic replacement (first occurrence only)
"The cat and the cat".replace("cat", "dog")
// returns "The dog and the cat"

// Global replacement of all occurrences
"The cat and the cat".replace("/cat/g", "dog")
// returns "The dog and the dog"

// Case insensitive replacement
"Hello HELLO hello".replace("/hello/gi", "hi")
// returns "hi hi hi"

Last updated

Was this helpful?