How to replace white space in from a String in Javascript?

    Apr 11, 2020       by Pankaj Kumar

While working with Javascript, We often need to replace a character with other characters and remove space from a string. For this task string functions are available, Regular expression can also be used to achieve the same task.

 

Replace a string with another using replace() function

var str = "Hello Ram, Hello Shyam Good Morning";

str.replace('Hello','Hi'); // output: Hi Ram, Hello Shyam Good Morning

 

Replace() function only replaces first match if we first argument as a string

 

Replace a string with another using Regular expression

var str = "Hello Ram, Hello Shyam Good Morning";

str.replace(new RegExp('Hello'), 'hi'); // output: Hi Ram, Hello Shyam Good Morning

 

A regular expression can be a single character or a more complicated pattern. Regular expressions can be used to perform all types of text search and text to replace operations.

 

Perform a global replacement:

Sometimes we need to replace all occurrences of a string with the one. The same can be done with below ways.

 

var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/g, "red"); // ouput:  Mr Blue has a red house and a red car

 

Perform a global, case-insensitive replacement:

var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/gi, "red"); // output: Mr red has a red house and a red car

 

 

Thank you!


WHAT'S NEW

Find other similar Articles here: