ThomasReggi ThomasReggi - 7 months ago 6
Javascript Question

Split string at first occurrence

I'm struggling splitting the following string into two pieces. Mainly because the one of the possible delimiters is a space character, which can appear in the second capture group.

https://regex101.com/r/dS0bD8/1

How can I split these strings at either

\s
,
\skeyword\s
, or
\skey\s
?

'[] []' // => ['[]', '[]']
'[] keyword []' // => ['[]', '[]']
'[] key []' // => ['[]', '[]']

'[] ["can contain spaces"]' // => ['[]', '["can contain spaces"]']
'[] keyword ["can contain spaces"]' // => ['[]', '["can contain spaces"]']
'[] key ["can contain spaces"]' // => ['[]', '["can contain spaces"]']

'{} {}' // => ['{}', '{}']
'{} keyword {}' // => ['{}', '{}']
'{} key {}' // => ['{}', '{}']

'{} {"can":"contain spaces"}' // => ['{}', '{"can":"contain spaces"}']
'{} keyword {"can":"contain spaces"}' // => ['{}', '{"can":"contain spaces"}']
'{} key {"can":"contain spaces"}' // => ['{}', '{"can":"contain spaces"}']

'string string' // => ["string", "string"]
'string keyword string' // => ["string", "string"]
'string key string' // => ["string", "string"]

Answer
(\skeyword\s|\skey\s|\s(?=.*[\[{]|[^\]}]+$))

Will work for all the cases you gave.
Demo here.