javascript
Remove all whitespaces from a string using javascript
If you have a String that contains multiple whitespaces in it and want to remove all the whitespace from that string then you can use the code examples used in this post. We will be removing them using regex and without using regex.
// define a string with multiple whitespace
const str = " Programming Is Fun ";
// remove whitespace using regex
const result = str.replace(/s/g, '');
// print the result
console.log(result);
Output
ProgrammingIsFun
Explanation
- Defined a Javascript string named str that contains multiple whitespaces.
- We are using the regex expression with the replace() function to remove whitespace from the string.
- The replace() function will return the string without any whitespace.
- Printing the result in the console window.
Remove all whitespaces from string using replaceAll() function
We can also use the repalceAll() function of Javascript to remove all the white spaces from a string. The repalceAll() function takes two arguments - separator and joiner.
separator: The String that you want to replace.
joiner: The string that will be placed in the place of the separator.
Syntax
String.replaceAll(separator, joiner)
Code Example
const str = " Programming Is Fun ";
const result = str.replaceAll(' ', '');
console.log(result);
Output
ProgrammingIsFun
const str = " Programming Is Fun ";
const result = str.split(' ').join('')
console.log(result);
If you do not want to use the regex in Javascript to remove all the whitespace from a String then you can use split() and join() functions.
In the above code example, we have defined a string with multiple whitespaces in it. Using the split() function we are splitting the string into an array and then joining the array using join() function with a blank string.
In the above code example, we have defined a string with multiple whitespaces in it. Using the split() function we are splitting the string into an array and then joining the array using join() function with a blank string.
Was this helpful?
Similar Posts
- Remove all cookies from the current website using Javascript
- Remove all false, null, undefined and empty values from array using Lodash
- Remove last character of a string in Javascript
- Remove new line separator from start and end positions of string in Javascript
- Javascript examples to remove url from a string
- Convert all characters to lowercase using toLowerCase() method in javascript
- Get all keys from an object using Javascript