Skip to content

backslash in string doesn't get escaped #83

Open
@namedots

Description

@namedots

This is causing misleading assertion messages on codewars.com whom I do not represent, but that's where I'm coming from:

TLDR: '\n' and '\\n' are represented the same. the rest of this poorly formatted post is just showing my work, hopefully that works for you.

import { assert } from 'chai'
assert.strictEqual('\n', '\\n')

part of output:

...
AssertionError: expected '\n' to equal '\n'
...

where the line terminator is escaped, but the backslash is NOT

so I grep around a bit in chai, and see this kind of thing:
129: , 'expected #{this} to equal #{exp}'
alright, so there's some home-grown string interpolation, seems promising, I keep following this..

  msg = msg
    .replace(/#\{this\}/g, function () { return objDisplay(val); })
    .replace(/#\{act\}/g, function () { return objDisplay(actual); })
    .replace(/#\{exp\}/g, function () { return objDisplay(expected); });

... keep following into loupe (now leaving chai)

var stringEscapeChars = new RegExp(
  "['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]",
  "g"
);
var escapeCharacters = {
  "\b": "\\b",
  "	": "\\t",
  "\n": "\\n",
  "\f": "\\f",
  "\r": "\\r",
  "'": "\\'",
  "\\": "\\\\"
};
var hex = 16;
var unicodeLength = 4;
function escape(char) {
  return escapeCharacters[char] || `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-unicodeLength)}`;
}
function inspectString(string, options) {
  if (stringEscapeChars.test(string)) {
    string = string.replace(stringEscapeChars, escape);
  }
  return options.stylize(`'${truncate(string, options.truncate - 2)}'`, "string");
}

alright, let me try that regex

> var stringEscapeChars = new RegExp(
...   "['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]",
...   "g"
... );
undefined
> stringEscapeChars.test('\n')
true
> stringEscapeChars.test('\\')
false

so I'm guessing that's it.
and then trying just loupe by itself:

    "node_modules/loupe": {
      "version": "3.1.2",
      "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.1.2.tgz",
      "integrity": "sha512-23I4pFZHmAemUnz8WZXbYRSKYj801VDaNv9ETuMh7IrMc7VuVVSo+Z9iLE3ni30+U48iDWfi30d3twAXBYmnCg=="
    }
import {inspect} from 'loupe'
let a = inspect('\n')
let b = inspect('\\n')
console.log({a, b})
{ a: "'\\n'", b: "'\\n'" }

yeah.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions