Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# JavaScript - string to an array

Posted on 2016-09-29
Medium Priority
53 Views
Just need an example of how to copy a string of numbers to an array.  I have a number attribute (UPC) that can contain either 11 or 12 digits and I need to loop through each digital.

Example; UPC  = 123456789012
1234457333
0
Question by:tmajor99
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 35

Accepted Solution

ste5an earned 1000 total points (awarded by participants)
ID: 41822248
Use .split():

``````var UPC = '1234457333';
var chars = UPC.split('');
for (var i = 0; i < chars.length; i++) {
console.log('char at pos ' + i + ': ' + chars[i]);
}
``````
1

LVL 58

Assisted Solution

Julian Hansen earned 1000 total points (awarded by participants)
ID: 41822658
No need to split - this also works
``````var UPC = '1234457333';
for(var i = 0; i < UPC.length;i++) {
console.log(UPC[i]);
}
``````
0

LVL 35

Assisted Solution

ste5an earned 1000 total points (awarded by participants)
ID: 41823102
btw, the question is do you want the digits as number or string?

``````var UPC = '1234457333';
var chars = UPC.split('');
var digits = []
for (var i = 0; i < chars.length; i++) {
console.log('char at pos ' + i + ': ' + chars[i] + ', data type: ' + typeof chars[i]);
digits.push(parseInt(chars[i]));
}

for (var i = 0; i < digits.length; i++) {
console.log('digits at pos ' + i + ': ' + digits[i] + ', data type: ' + typeof digits[i]);
}
``````
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
###### Suggested Courses
Course of the Month11 days, 6 hours left to enroll