Remove whitespaces from a string in javascript

Ever encountered a situation where you would need to remove whitespaces from a string in javascript for various reasons like formatting a string, formatting string information for API calls, etc.

The best way to remove multiple whitespaces from a string in javascript is by using a regular expression.

How to remove whitespaces from a string in javascript :

Suppose below is the string which needs to be formatted by removing the whitespaces.

    const string = 'string having white spaces ';

The regular expression we are going to use is

    (/\s/g,'')

So, the full code that you can use is

    const string = 'string having white spaces ';
    const formattedString = string.replace(/\s/g,'');

Note the new formatted string needs to be assigned to a different variable to be used with formatted string.