We will learn to understand how to replace all white spaces using JavaScript? There are several ways in which you can replace all white space using JavaScript.For all the examples we are going to look at, we have used the following string:

var str = 'hey there! hello there! hi hello!';

Achieving it with replace() function in JavaScript

Speaking of replace() function in JavaScript, it takes 2 arguments.

  • Regular expression or the string you wish to search for.
  • The string that will be used to replace if there are matches found with.

What if you wish to replace only the first match?

The Replace function only replaces the first occurrence if we specify the first argument as string. Let’s take a look at the example below:

str.replace('hello', 'hi');
// result: hey there! hi there! hello hello!

We can rewrite the first argument as a regular expression as well, as shown below:

// method 1: regular expression with enclosed between slashes
str.replace(/hey/, 'Ya all');
 

// method 2: calling the RegExp method
str.replace(new RegExp('hey'), 'yo');
// output: yo there! hello there! hello hello!

When it comes to writing regular expressions, literal notation can be a quick solution. However, we recommend calling RegExp object’s construction function for the same as it is an advantageous approach if you prefer having variables.

When it comes to the reserved characters of Regular Expressions (i.e.-/\^$*+? ()|[]{}), you must escape them using a backslash \.

Replacing All Occurrences of String Matches using JavaScript:

Now we will examine the case of replacing all occurrences of string matches. Here, in this case, the replace function must use a regular expression as the first argument. However, there has to have a “global” matching flag as well.

Let’s take a look at the example below:

var str = 'hey there! hello there! hello hello!';


// method 1: literal notation
str.replace(/hello/g, 'yo');
 

// method 2: RegExp object
console.log(str.replace(new RegExp('hello', 'g'), 'yo'));
// result: hey there! yo there! yo yo!

We have made it happen due to the g flag. What does it indicate? It simply stands for global search and replace.

Replacing string in case if case-insensitive search:

As you can see in the previous example, the kind of search and replace operation we did was case-sensitive. If you wish to perform a case-insensitive search and replace operation, then we can go for the i flag after the g flag, as shown below:

// method 1: literal notation
str.replace(/hello/gi, 'yo'); 
 
// method 2: RegExp object
console.log(str.replace(new RegExp('hello', 'gi'), 'yo'));
// result: hey there! yo there! yo yo!

How to use the join() and split() functions in JavaScript?

We will start with the split function: It will split a string into an array. However, here it will be done by a regular expression or string. As for the join function, we join an array of elements into a string. Here this function an optional string will be taken as an argument to join the array.

Case-insensitive search and replace for all matches:

str.split('hello').join('yo yo');

As you can see in the above example, we have done a case-insensitive search and replace.

// method 1: regular expression slashes method
str.split(/hello/i).join('yo');
// result: hey there! yo there! hi yo!


// method 2: Using RegExp
str.split(new RegExp('hello', 'i')).join('hi');
// result: hey there! hi there! hi hi!

Attempting A Custom Recursive Search And Replace

We have already mentioned that when we pass a string as the first argument, it only replaces the first occurrence in case of the replace function. Now that we are aware of this fact, we can come up with a recursive function which will go through the string again and again until it searches and replaces all matches.

Case-sensitive search and replace for all matches:

var str = 'hey there! hello there! hi hello!';

String.prototype.replaceAll = function (findStr, stringToReplace) {
  var str = this;

  // no match exists in string?
  if (str.indexOf(findStr) === -1) {
    // return string
    return str;
  }
  return (str.replace(findStr, stringToReplace)).replaceAll(findStr, stringToReplace);
}

// usage:
str.replaceAll('hello', 'hi');

Case-insensitive search and replace for all matches:

We already know the fact that regular expressions are helpful when it comes to case-insensitive searches. All that we have to do is to use the gi flag. In this case, we don’t have to rely on a recursive search and replace function at all.

var str = 'hey there! hello there! hi hello!';

String.prototype.replaceAll = function(stringToFind, stringToReplace) {
    var str = this;
    
    // escape regexp special characters in search string
    stringToFind = stringToFind.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&');
    
    return str.replace(new RegExp(stringToFind, 'gi'), stringToReplace);
};
 
// usage:
console.log(str.replaceAll('hello', 'hi'));
// output: hey there! hi there! hi hi!