-2

How to split strings into an array in javascript? I tried this below

const Vehicles = "Sedan" + "Coupe" + "Minivan"
  const Output = Vehicles.split(",")

   console.log(Output)

and the results was

["SedanCoupeMinivan",]

However I would like the results to instead be this below

["Sedan", "Coupe", "Minivan"]
manny
  • 347
  • 5
  • 19
  • 3
    Does this answer your question? [Javascript Split string on UpperCase Characters](https://stackoverflow.com/questions/7888238/javascript-split-string-on-uppercase-characters) – peterulb Aug 18 '22 at 20:28
  • 1
    To get what you want, you need to include the delimiter "," – Vasya Aug 18 '22 at 20:28

3 Answers3

2

Well there are 2 methods to this, either changing the string and adding commas or using match function.

Method 1:

const Vehicles = "Sedan," + "Coupe," + "Minivan"
const Output = Vehicles.split(",")

console.log(Output)

Method 2:

const Vehicles = "Sedan" + "Coupe" + "Minivan"
const Output = Vehicles.match(/[A-Z][a-z]+/g);

console.log(Output)

Both work perfectly.

x72
  • 74
  • 2
1

Your original string

const Vehicles = "Sedan" + "Coupe" + "Minivan"

results in "SedanCoupeMinivan" as the value of Vehicles.

Then you try to split that by a comma:

const Output = Vehicles.split(",")

As the orignal string that you tried to split does not contain a single comma, the result you got is quite what I would expect.

You could assemble the original string with commas:

const Vehicles = "Sedan" + "," + "Coupe" + "," + "Minivan"

and the split should work as you expected.

cyberbrain
  • 3,433
  • 1
  • 12
  • 22
0

The variable Vehicles is just ONE long string. You combined the three strings and made them one. You cannot go back. Unless you use substring (for example) to cut the string wherever you want...

If you want to split the string at a specific character, like , you need to make sure the string has , between each part you want to cut.

Ben
  • 21
  • 4