-
Jun 3rd, 2015, 01:54 PM
#1
Thread Starter
Addicted Member
JavaScript Array From Striing
Hi there
I have a string like this '[1,2,3,4,5]'
Ideally id like to turn this in to an array on integers, but i can deal with it as strings
the reason it is stored like that is because it has come from my model and is stored in a hidden field
I have come up with this way to convert it, but its not all that. Also it does only convert it to a string array.
Code:
$('#DaysList').val().replace('[','').replace(']','').split(',')
Does anyone know a better way?
Many thanks for any help
Regards
Ian
-
Jun 3rd, 2015, 07:08 PM
#2
Re: JavaScript Array From Striing
That's easy. Just run the string through JSON.parse(). It's supported in every browser including IE8+. If you need it in older browsers, you can use the JSON3 polyfill.
-
Jun 4th, 2015, 06:41 PM
#3
Thread Starter
Addicted Member
Re: JavaScript Array From Striing
Thanks tr333.
Thats great. Bit annoyed I didn't find that though.
Didn't think to use json I guess..
Thanks again Ian
-
Jun 6th, 2015, 08:59 AM
#4
Re: JavaScript Array From Striing
If you can't use JSON.parse
Code:
x.slice(1,-1).split(',').map(Number)
or
Code:
x.match(/\d+/g).map(Number)
Last edited by penagate; Jun 6th, 2015 at 09:02 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|