I have a simple code line:
var myarr = str.split(":");
This works if user enters 1:23
However, it is possible the user can enter one more format: 1.23
Without doing a manual check for strings, is there something I can add to this split function to enter multiple values?
2 Answers 2
Use a regular expression
String.split(/[:,.]+/)
Splits on : or , or .
1 Comment
As is described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
the split method on strings can be passed a regular expression. Regular Expressions are described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
This means you can split on anything that you can match with a regular expression. So for example:
var string = 'foo';
var array = string.split(/[:.]/);
will split on any character that is either : or ..
str.split(/[:.]/)