0

Is there any way in JavaScript to parse a string?

For example, I have this string named "band":

let band = "John,Paul,George,Ringo";

and I want to parse it based on comma as a delimiter. So, in the end I want to have four variables:

let name1 = "John";
let name2 = "Paul";
let name3 = "George";
let name4 = "Ringo";

How can I do that?

Spectric
  • 30,714
  • 6
  • 20
  • 43
brilliant
  • 2,805
  • 11
  • 39
  • 57
  • 1
    For this type of thing it is better to use an array: `const names = band.split(',')`, and then access the values using an index: `names[0]`, etc... – Nick Parsons Oct 03 '21 at 00:43
  • Does this answer your question? [How can I parse a CSV string with JavaScript, which contains comma in data?](https://stackoverflow.com/questions/8493195/how-can-i-parse-a-csv-string-with-javascript-which-contains-comma-in-data) – Tibrogargan Oct 03 '21 at 00:50

1 Answers1

1

You can split the string on a comma:

let band = "John,Paul,George,Ringo";
let members = band.split(',');
let john = members[0];
let paul = members[1];
let george = members[2];
let ringo = members[3];

This will give you an array called members which lets you access them using an index either directly or via a loop.

Depending on what browsers/environments you may need to support, you can destructure the array too:

let band = "John,Paul,George,Ringo";
let [john, paul, george, ringo] = band.split(',');

If you want loop over the members:

let band = "John,Paul,George,Ringo";
let members = band.split(',');

for (let i = 0; i < members.length; i++) {
    console.log(members[i]);
}

This would loop over all members in the array and log them to console, which you can modify to perform other things on each item in the array.

Marc Baumbach
  • 10,323
  • 2
  • 30
  • 45