Javascript - Replacing String Content

Introduction

The replace() method replaces a specified value with another value in a string:

Demo

var str = "this is A test";
var txt = str.replace("t","W");
console.log(txt);

Result

The replace() method does not change the original string. It returns a new string.

By default, the replace() function replaces only the first match:

Demo

var str = "this is a test";
var txt = str.replace("t","W");
console.log(txt);

Result

By default, the replace() function is case sensitive.

Demo

var str = "This is a Test";
var txt = str.replace("t","W");
console.log(txt);

Result

To replace case insensitive, use a regular expression with an /i flag (insensitive):

Demo

var str = "this is a test";
var txt = str.replace(/t/i,"W");
console.log(txt);

Result

To replace all matches, use a regular expression with a /g flag (global match):

Demo

var str = "this is a test";
var txt = str.replace(/t/g,"w");
console.log(txt);

Result

Related Topic