Results 1 to 4 of 4

Thread: JavaScript Array From Striing

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Sep 2008
    Location
    Reading, UK
    Posts
    192

    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

  2. #2
    Frenzied Member tr333's Avatar
    Join Date
    Nov 2004
    Location
    /dev/st0
    Posts
    1,605

    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.
    CSS layout comes in to the 21st century with flexbox!
    Just another Perl hacker,

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Sep 2008
    Location
    Reading, UK
    Posts
    192

    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

  4. #4
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    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
  •  



Click Here to Expand Forum to Full Width