qwertymk
qwertymk

Reputation: 35276

Split on Regex Not At Beginning of Line

I'm looking to split a string on spaces but not if those spaces are at the beginning of the line, here's what I have so far:

alert(JSON.stringify(
  '  this   is   a  test'.split(/(?!^\s+)\s+/)
))

but that only works if there's only one space in the beginning or the string.

I know that javascript doesn't support lookbehinds, is there anyway to do this without a hack like reversing the string?

Upvotes: 0

Views: 63

Answers (2)

anubhava
anubhava

Reputation: 785098

In Javascript this should work:

'   this   is   a  test'.split(/(^\s+\S+)|\s+/).filter(Boolean)
//=> ["   this", "is", "a", "test"]

i.e. group all the desired text on LHS of alternation and keep split pattern on RHS of pipe.

Upvotes: 1

Himanshu Tanwar
Himanshu Tanwar

Reputation: 906

alert(JSON.stringify(
  '  this   is   a  test'.trim().split(/(?!^\s+)\s+/)
))

Upvotes: 0

Related Questions