Skip to main content
javascript-string-replace-example

JavaScript String Replace Example

This tutorial help to understand javascript string replace with an example. The javascript has a replace() method that use to search and replace the string. You can search a constant string or regular expression.This method return the new string which has replaced word with in target string.

The main difference is between a fixed String or the RegExp pattern, The fixed value will use to replace only the first occurrence of the string whereas regular exp can be used to replace all occurrences of string using '/g'.

The replace syntax is –

string.replace(searchvalue|regexp, newvalue|function)

Where –

  • searchvalue|regexp Required – The value, or regular expression, that will be replaced by the new value.
  • newvalue|function Required – The value to replace the search value into the target string.

JavaScript String Replace With Fixed Value

Let’s take an example –

let oldStr = 'Hi, My name is Adam';
let newStr = oldStr.replace('Adam', 'Joe')

console.log(newStr);

Output: Hi, My name is Joe;

The replace() method does not change the existing string object, It just returns a new string object.

JavaScript String Replace With RegExp Pattern

We will take a sample string replace example, where we will replace string using RegExp pattern.

let oldStr = 'Hi, My name is Adam and living in Denver.The Denver, is the capital and most populous municipality of the U.S. state of Colorado. Denver is located in the South Platte River Valley on the western edge of the High Plains just east of the Front Range of the Rocky Mountains.';
let newStr = oldStr.replace(/Denver/g, 'Ohio')

console.log(newStr);

Output:

Hi, My name is Adam and living in Columbus.The Columbus, is the capital and most populous municipality of the U.S. state of Colorado. Columbus is located in the South Platte River Valley on the western edge of the High Plains just east of the Front Range of the Rocky Mountains.

You can also use multiple replace fixed strings using replace() method, You just need to chained method:

newStr = oldStr
  .replace('is', 'are')
  .replace('Colorado', 'Ohio');
  
console.log(newStr);

JavaScript Replace with function as Second Argument

We can also define a function as a second argument into replace method, The function will invoke each times once the pattern match –

let oldStr = 'I am adam and living into denver.';

newStr = oldStr.replace(/adam/g, (match) => {
  return match.toUpperCase()
});
console.log(newStr);

Output:

I am ADAM and living into denver.

We just searched adam into the target string and replace it with uppercase, The new string will return with ADAM.

Leave a Reply

Your email address will not be published. Required fields are marked *