Reputation: 9585
Consider a string:
12345678
The desired output is:
1 2 3 4 5 6 7 8
How can this be split using JavaScript?
Upvotes: 2
Views: 10560
Reputation: 21
$(document).ready(function() {
var s = "12345678";
$('#s').html(s);
var letters = s.split('').join(' ');
$('#letters').html(letters);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id='s'></label><br/><label id='letters'></label>
Upvotes: 2
Reputation: 23753
My guess is he just wants to put spaces in between the numbers. How about:
str = "1234567890";
var splitStringArray = str.split("");
var finalString = "";
for(var i = 0; i < splitStringArray.length; i++) {
finalString += splitStringArray[i];
if (i < splitStringArray.length-1) {
finalString += " ";
}
}
Upvotes: -1
Reputation: 532445
No need for jQuery to split a string. Use pure javascript.
var s = "12345678";
var letters = s.split(''); // results in [ '1', '2', '3', .... ]
Upvotes: 14
Reputation: 191
split to what? if you want to split each character to array element, use javascript split() method :
var str = "12345678";
var arr = str.split("");
Upvotes: 8
Reputation: 1706
no jquery needed, you can split string using regular javascript split function.
<script type="text/javascript">
var str="12345678";
var splittedStr = str.split("");
</script>
Upvotes: 2
Reputation: 268324
You should use straight Javascript for this:
var string = "12345678";
var parts = string.split('');
Upvotes: 4