简体   繁体   中英

Javascript: remove quotes from string of comma separated numbers

I have a string

var s = "2,4,6,8,10"

I need output 2,4,6,8,10

Convert this string to int? Is this at all possible?

You mean to turn a string of numbers to an array of numbers? something like this:

 var s = "2,4,6,8,10"; var numberArray = s.split(',').map(i => +i); console.log(numberArray);

Note: changed it to from Number(i) to +i , simpler and cleaner imo

You can split the string by commas and then parseInt each string and get an array of numbers.

 let s = "2,4,6,8,10" let splitted = s.split(','); console.log(splitted); let parsed = splitted.map(x => parseInt(x)); console.log(parsed);

You can convert it into an array of numbers:

 let s = "2,4,6,8,10"; s = s.split(","); s.forEach((i, index) => { s[index] = parseInt(i); }) console.log(s)

I believe you are looking for something like this.

  1. split the string into substrings which each contain one number
var arrayOfStrings = s.split(",");
  1. convert these strings to numbers
var arrayOfNumbers = arrayOfStrings.map(s => parseInt(s))
  1. log the array of numbers
console.log(...arrayOfNumbers)

combined

 var s = "2,4,6,8,10" console.log(...s.split(",").map(item => parseInt(item))); console.log("or") console.log(s.split(",").map(item => parseInt(item)));

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