How to replace unicode escape character in Dart

Viewed 1681

I need to clean up a string that has an escape character but couldn't do so.

Here is my test code:

test('Replace unicode escape character', () {
    String originalText = 'Jeremiah  52:1\\u201334';
    String replacedText = originalText.replaceAll(r'\\', r'\');
    expect(replacedText, 'Jeremiah  52:1\u201334');
  });

It fails with an error:

Expected: 'Jeremiah  52:1–34'
  Actual: 'Jeremiah  52:1\\u201334'
   Which: is different.
          Expected: ... miah  52:1–34
            Actual: ... miah  52:1\\u201334
1 Answers

Unicode characters and escape characters aren't stored the way you write them when you wrote the string -- they are converted to their own values. This is evident when you run the following code:

print('\\u2013'.length); // Prints: 6
print('\u2013'.length);  // Prints: 1

Here, what happened was: the first stored the following characters: '\', 'u', '2', '0', '1', and '3' -- while the latter stored '–' only.

Hence, your attempt to change the first by replacing two slashes \\ with one slashes \ wouldn't work, as the compiler isn't converting your unicode escape characters any longer.

That doesn't mean that you won't be able to convert your unicode codes into unicode characters though. You could use the following code:

final String str = 'Jeremiah  52:1\\u2013340';
final Pattern unicodePattern = new RegExp(r'\\u([0-9A-Fa-f]{4})');
final String newStr = str.replaceAllMapped(unicodePattern, (Match unicodeMatch) {
  final int hexCode = int.parse(unicodeMatch.group(1), radix: 16);
  final unicode = String.fromCharCode(hexCode);
  return unicode;
});
print('Old string: $str');
print('New string: $newStr');
Related