marijnh / Eloquent-JavaScript

The sources for the Eloquent JavaScript book
https://eloquentjavascript.net
3.01k stars 795 forks source link

Ch. 9 – dea+hl[]rd #403

Closed mikegowen closed 6 years ago

mikegowen commented 6 years ago

In this example:

let name = "dea+hl[]rd";
let text = "This dea+hl[]rd guy is super annoying.";
let escaped = name.replace(/[\\\[.+*?(){|^$]/g, "\\$&");
let regexp = new RegExp("\\b" + escaped + "\\b", "gi");
console.log(text.replace(regexp, "_$&_"));
// → This _dea+hl[]rd_ guy is super annoying.

Do you need that 3rd backslash at the beginning?

/[\\\[.+*?(){|^$]/g https://scrn.es/WU5OBMAXhGTQHmYR6BuVi

vs.

/[\\[.+*?(){|^$]/g https://scrn.es/4GiJj6ScfTCD22kmrLY1Dh

If i'm following, the first two represent an escaped backslash. Which means the 3rd one is escaping the open bracket. But do you need to do that here?

marijnh commented 6 years ago

If i'm following, the first two represent an escaped backslash. Which means the 3rd one is escaping the open bracket.

Not strictly—I guess I might as well remove it. See attached patch.