Home > Mobile >  How to split strings into an array in javascript?
How to split strings into an array in javascript?

Time:08-19

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"]

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related