Vicky
Vicky

Reputation: 9585

Inserting spaces between numbers in a string

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

Answers (7)

Manish kumar Agarwal
Manish kumar Agarwal

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

MegaMatt
MegaMatt

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

tvanfosson
tvanfosson

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

David Hellsing
David Hellsing

Reputation: 108480

'12345678'.split('').join(' ');

Upvotes: 14

c1h4nd
c1h4nd

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

Numenor
Numenor

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

Sampson
Sampson

Reputation: 268324

You should use straight Javascript for this:

var string = "12345678";
var parts  = string.split('');

Upvotes: 4

Related Questions