buydadip
buydadip

Reputation: 9417

JavaScript split on multiple delimiters and preserve quoted text

I have the following string...

'(!false >=stuff 300 OR 200 "TEST DATA")'

I figure out how to preserve quoted text using the following...

test.match(/\w+|"[^"]+"/g)

However, the output is not what I want...

[ 'false', 'stuff', '300', 'OR', '200', '"TEST DATA"' ]

There is a list of symbols I need to preserve...

{'<', '>', '<=', '=>', '=', '!'}

so that my split should look as follows...

['(', '!', 'false', '>=', 'stuff', '300', 'OR', '200', '"TEST DATA"', ')']

How can I add onto my match function to preserve the following? I'm not very good with regex.

Upvotes: 0

Views: 48

Answers (1)

anubhava
anubhava

Reputation: 785186

You may use:

let str = '(!false >=stuff 300 OR 200 "TEST DATA")'

let arr = str.match(/"[^"]*"|[<>]=|[^\w\s]|\w+/g)

console.log(arr)
//=> ["(", "!", "false", ">=", "stuff", "300", "OR", "200", ""TEST DATA"", ")"]

Regex has following alternatives:

  • "[^"]*": Match a quoted string
  • [<>]=: Match <= or >=
  • [^\w\s]: Match any non-space, non-word character
  • \w+: Match any word

Upvotes: 1

Related Questions