简体   繁体   中英

How to split strings into an array in javascript?

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM