meandre meandre - 1 year ago 71
Javascript Question

Split the sentences by ',' and remove surrounding spaces

I have this code:

var r = /(?:^\s*([^\s]*)\s*)(?:,\s*([^\s]*)\s*){0,}$/
var s = " a , b , c "
var m = s.match(r)
m => [" a , b , c ", "a", "c"]

Looks like the whole string has been matched, but where has
gone? I would rather expect to get:

[" a , b , c ", "a", "b", "c"]

so that I can do
with a result like
but also with whitespaces removed.

Do I have a mistake in the regexp or do I misunderstand

Answer Source

so finally i went with /(?=\S)[^,]+?(?=\s*(,|$))/g, which provides exactly what i need: all sentences split by ',' without surrounding spaces.

'       a,    OMG     abc b a b, d o WTF        foo     '.
  match( /(?=\S)[^,]+?(?=\s*(,|$))/g )
=> ["a", "OMG     abc b a b", "d o WTF        foo"]

many thanks!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download