John Smith
John Smith

Reputation: 39

Getting All Values from Comma Separated String in Javascript

I have 1 String Variable in JavaScript which contains 3 Comma separated values shown below:

var session = "[email protected],123456,f_id=8";

I want to get all above 3 comma separated values in 3 different variables. What I have achieved so far is getting last comma separated value in elem2 variable and getting other 2 comma separated values 1st and 2nd one in elem1 variable.

var elem1 = session.split(",");

var elem2 = elem1.pop();

document.write("elem1 = "+elem1+"<br/>elem2 = "+elem2);

So my program is not working fine as I wants, please I need quick working solution so that I have another variable elem3 and I will get following output in my browser:

elem1 = [email protected]
elem2 = 123456
elem3 = f_id=8 

Upvotes: 1

Views: 1845

Answers (3)

Tom Ritsema
Tom Ritsema

Reputation: 468

You could also use string.replace with a callback as parameter. Very flexible!

Check this for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

For your usecase you may end up with:

function writeParts(match, email, number, id, offset, string) {
    document.write("email = "+email+"<br/>number = "+number);
}
// match not-comma followed by a comma (three times)
session.replace(/([^,]+),([^,]+),([^,]+)/, writeParts);

Upvotes: 0

user1585455
user1585455

Reputation:

You can also store the session data in a JavaScript Object. Below iterates through each split string and adds it to an Object.

var myData = {};

// ...

for(var i = 0, x = session.split(","); i < x.length; i++) {
    switch(i) {
        case 0: myData.email = x[i]; break;
        case 1: myData.number = x[i]; break;
        case 2: myData.f_id = x[i]; break;
    }
}

If you're dealing with multiple data values, it's best to make an array of objects, like so.

var myData = [];

// ...

myData.push({
    email: x[0],
    number: x[1],
    f_id: x[2]
});

And so on. This is a form of JSON Notation. The output would look like this:

[
    {
        email: "[email protected]",
        number: "123456",
        f_id: "f_id=8"
    },
    {
        // Another session, etc.
    }
]

Upvotes: 0

Christos
Christos

Reputation: 53958

You could try the following:

// Initially, we split are comma separated string value on commas.
// In the values an array of these values is stored.
var values = session.split(",");
// Then we get each value based on it's position in the array.
var email = values[0];
var number = values[1];
var id = values[2];

As a side note, I would suggest you use meaningful names for your variables like above. The names elem1, elem2 and elem3 are a bit vague and in future thses namings may obscure even you, let alone another reader of your code.

Upvotes: 5

Related Questions