Split String by Single Space
To split a string by single space character in JavaScript, call split() method on the given string and pass single space delimiter string as argument in the method call.
The expression to split a string str
by single space delimiter is
</>
Copy
str.split(' ');
Example
In the following example, we take a string in str
, split the string by single space 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 cherry';
var values = str.split(' ');
for(index = 0; index < values.length; index++) {
document.getElementById('output').innerHTML += values[index] + '\n';
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to split the given string by single space delimiter using String.split() method, with example program.