0

I have a bunch of strings that look like

"The\\u00a0discrepancies\\u00a0experienced"

and I want to filter out the \\u00a0 and replace them with ' '

Naively I tried something like

const unicodeRegexp = new RegExp('\\u00a0', 'g')
const filterKey = string => string.replace(unicodeRegexp, ' ')

but a quick test of filterKey("The\\u00a0discrepancies\\u00a0experienced") returns the string unfiltered.

What's going on here?

Dave Sag
  • 13,266
  • 14
  • 86
  • 134
  • Do the strings contain two literal backslashes before the `u`, or one? – CertainPerformance Jan 11 '19 at 02:34
  • The \ needs to be escaped. – holydragon Jan 11 '19 at 02:34
  • 1
    Don't ever use `new RegExp` unless you need to dynamically create a pattern from a variable - use regex literals instead, to avoid the need for double-escaping – CertainPerformance Jan 11 '19 at 02:36
  • so in summary my filter is fine, it's the input strings that are wrong. I should be filtering `"The\u00a0discrepancies\u00a0experienced"` instead. I got my input string by copying some output from the console. Therein lay my error. – Dave Sag Jan 11 '19 at 02:57
  • @DaveSag For a string containing double backslashes, you will need to escape each of the backslashes in the regex. The most straightforward way then, is to write `string.replace(/\\\\u00a0/g, ' ');` But if you want to use a string literal as an input to a regExp object, then you will need to escape each of those backslashes _again_, resulting in `const unicodeRegexp = new RegExp('\\\\\\\\u00a0', 'g');` That is why a RegExp object is not recommended in this case. – Mr Lister Jan 11 '19 at 08:26

0 Answers0