Split String by any White Space Character
To split a string by any white space character like single space, tab space, new line, etc., in JavaScript, call split() method on the given string and pass a regular expression that matches any white space character.
The expression to split a string str
by any white space character is
str.split(/(\s)/)
The above expression returns an array with with the white space characters in the string as array items. If we want an array without these whitespace characters, we may filter them using the following expression.
str.split(/(\s+)/).filter((x) => x.trim().length>0)
Example
In the following example, we take a string in str
with single space, tab, and new line characters, split the string by any white space character as delimiter, and display the splits array in pre#output.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var str = `apple banana\tcherry\nmango`;
var values = str.split(/(\s)/).filter((x) => x.trim().length>0);
for(index = 0; index < values.length; index++) {
document.getElementById('output').innerHTML += index + ' - ' + values[index] + '\n';
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to split the given string by any white space character as delimiter, using String.split() method, regular expression for one or more whitespaces, and Array.filter() method.