JavaScript Code

String replace() in JavaScript


String replace()

In JavaScript, String.replace() method is used to replace a specific search string in the string, with a replacement string.

Syntax

str.replace(search, replacement)

where

  • str is a string.
  • replace is function name.
  • search is a string or regular expression.
  • replacement is a string.

replace() method replaces the first occurrence of search string or regular expression with the replacement string in the string str, and returns the resulting string. replace() method does not modify the original string.

Examples

1. In the following program, we take a string in variable str, and then we replace the search string 'banana' with the replacement string 'mango' in str.

let str = 'apple banana cherry banana cherry';
let output = str.replace('banana', 'mango');
console.log(output);

2. In the following program, we take a string in variable str, and then we replace the string that matches the search string 'banana' case insensitive and replace it with the string 'mango'.

let str = 'apple BANANA cherry banana cherry';
let output = str.replace(/banana/i, 'mango');
console.log(output);


Copyright @2022