0

I have a variable which includes a sting with numeric values such as "3, 6, 12". Each of these numbers correspond to another value that I need to assign to an object and pass on, in a later process. What would be the best way for me to split this string up in order to evaluate the numbers inside of this string? I would like to be able to evaluate this string and realize that there are 3 values in this string (which are 3, 6, 12, need to make sure that the "12" is not evaluated as "1" and "2"). Furthermore, how could I go about ignoring the commas and spaces inside of this variable? What would be the best way for me to extract these numeric values and ignore the spaces and commas in the process?

sdfssdf
  • 11
  • 2

2 Answers2

4

Try this:

"3, 6, 12".split(", ")

If you can have values with or whitout whitespaces, you can use the following to always get just the numbers:

"3, 6, 12".split(",").map(Number)
tiagodws
  • 1,345
  • 13
  • 20
  • 1
    So where did you get the idea to add `.map(Number)`? ;-) – trincot Jul 14 '17 at 22:30
  • "If you can have values without spaces, ..." `Number` can deal with whitespace, you don't need to `trim()` before converting it. But if you're concerned about that, how about `map(parseFloat)` this also deals with strings that contain other characters after the Number. – Thomas Jul 14 '17 at 22:48
  • @trincot I thought about adding it previously, but was unsure how it dealt with the whitespaces. Updated my answer after I tested it. – tiagodws Jul 15 '17 at 19:23
  • @Thomas Never used trim() on my answer :s Just said it to be clear that whitespaces weren't a problem when converting to number, because only split(",") would return the values with the whitespaces still there, if any. If the given string is guaranteed to follow the pattern thought, this would never be a problem. – tiagodws Jul 15 '17 at 19:36
3

You could use a regular expression and then apply Number to get number typed array elements:

var arr = str.match(/[\d.]+/g).map(Number)

This will ignore spaces, commas, and any other non-digit character (except a decimal point, which will be taken into account).

trincot
  • 317,000
  • 35
  • 244
  • 286