How to get numbers from strings
-
I have a function that iterate over strings like
strings = ["brass", "001", "127", "flute"]How can I find the string numbers from this array?
I have tried "typeof", of course that's not going to work, eval(), etc....
I even tried to let all strings passEngine.getMidiNoteName(string)and it log "0" for all letter strings but it works for the "number" strings
How do you do it? -
@ulrik
I'm not sure I fully understand your question, but there isString.getIntValue(). This function converts a string into an integer.And there is
Engine.getValueForText(String text, String convertedMode). -
Use
parseInt. But you need to check the charcode of the first character to get rid of letter parsing returning0const var strings = ["brass", "001", "127", "flute"]; for (s in strings) { if (s.charCodeAt(0) >= 48 && s.charCodeAt(0) <= 57) // <= 0-9 numbers only Console.print(parseInt(s)); }As @Oli-Ullmann said
String.getIntValue()also works, I don't know if there's any difference between the two... -
@ulrik Or use regex to detect strings that only contains digits.
const var strings = ["brass", "001", "127", "flute"]; for (s in strings) { if (Engine.matchesRegex(s, "^\\d+$")) Console.print(parseInt(s)); }^means 'start of string'
\\dmeans digit
+means 'one or more'
$means 'end of string`So, "one or more digits between the start and end of the string, and nothing else"
-
@ulrik said in How to get numbers from strings:
How can I find the string numbers from this array?
How did the numbers get into the array as strings?
-
@ulrik are you parsing dodgy data from somewhere?? Because grouping numbers and text strings like that into a single array seems like a poor design.