JVG
JVG

Reputation: 21150

Take words from string and convert to array

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?

Upvotes: 1

Views: 201

Answers (2)

schnill
schnill

Reputation: 955

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

Upvotes: 0

falsetru
falsetru

Reputation: 369094

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"]

Upvotes: 3

Related Questions