nepsilon / search-query-parser

A simple parser for advanced search query syntax
https://www.npmjs.org/package/search-query-parser
MIT License
251 stars 40 forks source link

Stringify/parse mismatch when a keyword has multiple values which one of them includes a space #55

Open roysharon opened 9 months ago

roysharon commented 9 months ago

When using a keyword with multiple values that one of them includes a space, stringify method works as expected, but parse does not produce the same query:

import parser from 'search-query-parser' 

const options = { keywords: ['brakes'], offsets: false }
const orgQuery = { brakes:['foo bar', 'choo'], exclude: {} }
const stringified = parser.stringify(orgQuery, options)
// stringified = 'brakes:"foo bar",choo'
const destQuery = parser.parse(stringified, options)
// destQuery = { text: ',choo', brakes: 'foo bar', exclude: {} }
roysharon commented 9 months ago

For anybody encountering this bug here is a workaround until it is fixed:

import parser from 'search-query-parser' 

const options = { keywords: ['brakes'], offsets: false }
const orgQuery = { brakes:['foo bar', 'choo'], exclude: {} }
let stringified = parser.stringify(orgQuery, options)
// stringified = 'brakes:"foo bar",choo'
// workaround start
const replacements = []
stringified = stringified.replace(/"([^"]*)"/g, (match, p1) => {
  replacements.push(p1)
  return `__${replacements.length - 1}__`
})
const destQuery = parser.parse(stringified, options)
Object.entries(destQuery).forEach(([key, value]) => {
  if (Array.isArray(value)) {
    destQuery[key] = value.map(v => v.replace(/__(\d+)__/g, (match, p1) => replacements[p1]))
  }
})
// workaround end
// destQuery = { brakes: [ 'foo bar', 'choo' ], exclude: {} }