Skip to main content

Command Palette

Search for a command to run...

JavaScript String Replace & ReplaceAll

Updated
1 min readView as Markdown
JavaScript String Replace & ReplaceAll
J

Hello, I'm a Software Engineer.

JavaScript-String-Replace-By-Examples.jpeg

The replace() method in JavaScript is only replace first occurrence of a substring.

The replace() method accept two parameters.

Example :

const str = "I have Red Car and Red Bike";
const res = str.replace("Red","Blue");
console.log(res); // I have Blue Car and Red Bike.

To Perform a global search to replace all occurrences from a string you can use regular expression with global modifier :

const str = "I have Red Car and Red Bike";
const res = str.replace(/red/gi,'Blue');
console.log(res); // I have a Blue Car and Blue Bike.

Here g means it searches globally in string, and it means it ignoring cases of substring.

Like This Article. 👍 You can also Follow.

More from this blog

J

JavaScript Blogs

19 posts

Hello I'm Software Engineer.