In JavaScript, there are several different ways to filter out whitespace from a string. This article attempts to illustrate ways you can do that with the whitespace characters in your strings by showing you how to do it in five ways:
- Using Loops
- Using An Array Method: Split/Filter/Join Methods
- Using Array Methods: Split/Join
- Using Replace Method
Using Loops
When we use for loops, we have to declare a new string variable prior to the loop so we can add to it as we go.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <style> body { font-family: 'Roboto', Courier, monospace } </style> <script> const handleSubmit = str => { //loop let newStr = ""; for(let i = 0; i < str.length; i++) { if(str[i] !== " ") { newStr += str[i]; } } document.getElementById("demo").innerHTML = newStr; } </script> </head> <body> <h1>Whitespace Filter</h1> <input id="demoString" value="" type="text" name="inputString" placeholder="I'm a string"/> <input type="submit" onclick="handleSubmit(demoString.value)"/> <div id="demo"></div> </body> </html>
The loop looks at each individual character to see if it’s a whitespace character. If it’s not, it adds it to the newStr variable. To serve our purpose here, we insert it into the Document Object Model (DOM) so we can see it on screen. If you need to use it elsewhere in your code, you would return the newStr variable.
Using An Array Method: Split/Filter/Join Methods
Closely related to the loop method explained above, the split/filter method takes a string, splits it into an array and then uses the ES6 method filter that removes whitespace. Here’s how to do it:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <style> body { font-family: 'Roboto', Courier, monospace } </style> <script> const handleSubmit = str => { //split/Filter const splitted = str.split(''); const filtered = splitted.filter(char => { return char !== " "; }) let newStr = filtered.join(''); document.getElementById("demo").innerHTML = newStr; } </script> </head> <body> <h1>Whitespace Filter</h1> <input id="demoString" value="" type="text" name="inputString" placeholder="I'm a string"/> <input type="submit" onclick="handleSubmit(demoString.value)"/> <div id="demo"></div> </body> </html>
Using Array Method: Split/Join
In the previous section, we used split, filter and join to remove the spaces from a string. In reality, we only need to use the split and join methods if we use array methods. All we need to do is split on the space and then join each character!
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <style> body { font-family: 'Roboto', Courier, monospace } </style> <script> const handleSubmit = str => { //split/join const splitted = str.split(' '); let newStr = splitted.join(''); document.getElementById("demo").innerHTML = newStr; } </script> </head> <body> <h1>Whitespace Filter</h1> <input id="demoString" value="" type="text" name="inputString" placeholder="I'm a string"/> <input type="submit" onclick="handleSubmit(demoString.value)"/> <div id="demo"></div> </body> </html>
What an interesting little shortcut! You can split on a character of your choice to cut that character out of your string completely and then join the array back together on the individual character to get your string.
Using Replace Method:
The replace method is great to use when you want to use RegEx to filter out all of the spaces in your strings. We need to use RegEx here because replace, by definition, replaces the first instance of what it’s looking for. If we have multiple spaces in our string, the replace method will only take out the first space – unless we use a regular expression for identifying white space.
The global flag at the end of the regular expression is what allows us to search and replace for more than one instance.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <style> body { font-family: 'Roboto', Courier, monospace } </style> <script> const handleSubmit = str => { let regex = /\s+/g let newStr = str.replace(" ", ""); document.getElementById("demo").innerHTML = newStr; } </script> </head> <body> <h1>Whitespace Filter</h1> <input id="demoString" value="" type="text" name="inputString" placeholder="I'm a string"/> <input type="submit" onclick="handleSubmit(demoString.value)"/> <div id="demo"></div> </body> </html>
The \s is a whitespace character and the + indicates we are looking for one or more whitespace characters that are grouped in a row. The g at the end of the expression, as a reminder, indicates we are looking for multiple different groupings of whitespace characters.
Conclusion
In this article we’ve covered four ways to take out the white space from a storing in JavaScript. We used loops, the filter method, the split/join methods and regular expressions. Learning how to do these basic things in JavaScript will give you the tools you need to solve even more complex problems in JavaScript as you progress on your journey!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.