Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert raw string to string

Tags:

flutter

dart

If I print a raw string e.g.

String raw = r'\n\n\n';
print('Output: $raw');
// Output: \n\n\n

I gets exactly these characters. But what do I have to do to get three empty lines, i.e. unescaping the raw string?

I could replace the characters one by one with

String unRaw = raw.replaceAll(r'\n', '\n');

but unfortunately I'd have to do that with every escape sequence, which is error-prone.

Context: I get the raw string from a user via a textfield and want to interpret it as a normal string.

like image 475
Till Friebe Avatar asked Oct 19 '25 13:10

Till Friebe


1 Answers

I think there is no direct method to do it, check this. There is a third-party package that claims to do it.

However, I think there is workaround that can be done is using a jsonDecoder for your case here.

jsonDecoder can decode strings too, hence construct a raw json, then decode it to get your string.

Example:

import 'dart:convert';

main(){
    String value = r'a\nb';
    print(value); // prints raw string
    value = jsonDecode(r'{ "data":"'+value+r'"}')['data']; // converted to escaped string
    print(value); // prints a & b in different lines
}

Hope that helps!

like image 182
Hemanth Raj Avatar answered Oct 22 '25 03:10

Hemanth Raj