0

I have following string in javascript variable

var days="1,2,3";

now I want this in following way as javascript variable with JSON format like

jdays=["1", "2", "3"];

Is there anyway to do so?

Muhammad Usman
1,3625 gold badges19 silver badges35 bronze badges
asked Oct 9, 2015 at 10:12
7
  • 1
    You want to remove 3? Try days.split(',');, or days.match(/\d+/g) Commented Oct 9, 2015 at 10:12
  • jdays = days.split(',') ? Commented Oct 9, 2015 at 10:13
  • @Tushar - no I don't want to remove 3, I have updated my question.please let me know if any solution. Commented Oct 9, 2015 at 10:14
  • That has nothing to do with json... Commented Oct 9, 2015 at 10:15
  • 1
    @skiskd That is not JSON, it'a an array, check my previous comment to get the data in the array format Commented Oct 9, 2015 at 10:16

3 Answers 3

1

This will work

var days = "1,2,3",
 jdays = days.split(',');
console.log(jdays); // ["1", "2", "3"]

String.prototype.split() is used to split a string into an array by removing every instance of the string passed to it as a parameter and pushing each fragment of the string to the array.

The array created by String.prototype.split() is the return value of the function.

answered Oct 9, 2015 at 10:58
Sign up to request clarification or add additional context in comments.

2 Comments

FYI console.log(jdays); // [1, 2, 3] is wrong, jdays will be ["1", "2", "3"], note that the elements of array are strings not numbers
@Tushar Didn't see that... Thanks.
1

by using split function you can do this

 var daysArr = days.split(',') 
answered Oct 9, 2015 at 10:15

Comments

0

If, when you say you "want this in following way as a javascript variable" you mean you want that JSON format string in a variable.. then..

jsonstring = 'jdays='+JSON.stringify(days.split(','));
answered Oct 9, 2015 at 10:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.