1

Seems simple enough but I can't find an answer on Stack that has a good solution. Feel free to point me in the right direction.

The regex should allow me to do a javascript split to convert a string into an array. The basic test is that:

test1 test2, tes-t3; t"e's-----4.      test5

should be split into an array that contains:

[test1, test2, tes-t3, t"e's-----4, test5]

Best way to achieve this?

1
  • 1
    I don't see any regex...What have you tried so far? Check here regular-expressions.info Commented Jul 25, 2013 at 4:06

2 Answers 2

3

Use String.split(/[\s,;.]+/):

var s = 'test1 test2, tes-t3; t"e\'s-----4.      test5';
s.split(/[\s,;.]+/)
=> ["test1", "test2", "tes-t3", "t"e's-----4", "test5"]

or String.match(/[-'"\w]+/g):

s.match(/[-'"\w]+/g)
=> ["test1", "test2", "tes-t3", "t"e's-----4", "test5"]
Sign up to request clarification or add additional context in comments.

7 Comments

maybe you should use regex [\s,;\.]+ to split instead of [\s,;.]+?
@Angga, You don't need to escape dot(.) inside [].
Is there a way to modify this so that it doesn't count ending spaces? Currently if the input has var s = 'test1 ' (space at the end) it splits to ['test1', ''].
@Jascination, Which one do you want as a result: ['test1 '] (with trailing space remained), ['test1'] (no trailing space)?
The latter, ['test1']. Apologies, it's hard to be super-specific with questions when you're new to this sort of thing!
|
0

try this also, "test1 test2, tes-t3; t\"e's-----4. test5".split(/\s+|[,.;]\s*/);

Comments

Your Answer

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.