inserting spaces between numbers in a string
Consider a string:
12345678
The desired o开发者_如何学JAVAutput is:
1 2 3 4 5 6 7 8
How can this be split using Javascript?
No need for jQuery to split a string. Use pure javascript.
var s = "12345678";
var letters = s.split(''); // results in [ '1', '2', '3', .... ]
'12345678'.split('').join(' ');
split to what? if you want to split each character to array element, use javascript split() method :
var str = "12345678";
var arr = str.split("");
You should use straight Javascript for this:
var string = "12345678";
var parts = string.split('');
no jquery needed, you can split string using regular javascript split function.
<script type="text/javascript">
var str="12345678";
var splittedStr = str.split("");
</script>
<html>
<head>
<script type = "text/javascript" src = "jquery.js"></script>
<script>
$(document).ready(function(){
var s = "12345678";
$('#s').html(s);
var letters = s.split('').join(' ');
$('#letters').html(letters);
});
</script>
</head>
<body>
<label id='s'></label><br/><label id='letters'></label>
</body>
</html>
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 += " ";
}
}
精彩评论