Removing Whitespaces from a String
- Regular expression
- split() with join()
Let’s understand each of these one by one, how they work along with examples for your better understanding.
console.log(example); //without using the method
console.log(example.replace(/ /g,'')); //with the replace() method
In order to remove all the whitespaces and not just the space character then you can use “\s” which will match against all the newline character, space character, tab character and translate it into a simpler code.
spit() with join()
You can also use \s for removing all the whitespace characters from the string.
To remove whitespaces from only the beginning or end of the string we’ll use trimStart() and trimEnd() methods.