2

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?

CIRCLE
4,9695 gold badges42 silver badges59 bronze badges
asked Oct 15, 2013 at 22:34
3
  • You can split on regular expressions, though that has some issues. Commented Oct 15, 2013 at 22:37
  • Can you use regex? str.split(/[:.]/) Commented Oct 15, 2013 at 22:37
  • 1
    To avoid the issues mentioned by Pointy you could have 2 arrays (one split on ":" and the other on ".") then take the longest. Commented Oct 15, 2013 at 22:46

2 Answers 2

4

Use a regular expression

String.split(/[:,.]+/)

Splits on : or , or .

answered Oct 15, 2013 at 22:37
Sign up to request clarification or add additional context in comments.

1 Comment

@KickingLettuce When in doubt, check the docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
0

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 ..

answered Oct 15, 2013 at 22:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.