split-string icon indicating copy to clipboard operation
split-string copied to clipboard

Escaped backslash before quote

Open derek-miller opened this issue 6 years ago • 2 comments

It appears the logic for when to respect a quote vs an escaped quote does not consider if the preceding escape char is itself escaped. For example:

$ node
Welcome to Node.js v12.3.1.
Type ".help" for more information.
> const split = require('split-string')
undefined
> console.log(split('\\\\"hello world\\\\"', { separator: ' ', quotes: ['"'] }))
[ '\\\\"hello', 'world\\\\"' ]
undefined
>

I would expect this to be [ '\\\\"hello world\\\\"' ].

Thoughts?

derek-miller avatar Oct 24 '19 19:10 derek-miller

I agree with this and did a quick test to see if adding the following here would help:

  const closeIndex = (value, startIdx) => {
    let idx = string.indexOf(value, startIdx);
    if (idx > -1 && (string[idx - 1] === '\\' && string[idx - 2] !== '\\')) {
      idx = closeIndex(value, idx + 1);
    }
    return idx;
  };

For this case it passes, but I haven't tried this change with the other tests. I'll try to get to this over the weekend unless someone else does a PR with the new test cases before that.

Thanks for the issue!

doowb avatar Oct 24 '19 20:10 doowb

@doowb Unfortunately that fix is too simplistic, if the string were \\\\\\"hello world\\\\" then the quote would be properly escaped but would still satisfy string[idx - 1] === '\\' && string[idx - 2] !== '\\'.

derek-miller avatar Oct 24 '19 22:10 derek-miller