3

I want to convert an existing string to raw string.

like:

String s = "Hello \n World"

I want to convert this s variable to raw string(I want to print exact "Hello \n Wrold")

I need backslash(\) in output. I am trying to fetch string value from rest api. it have bunch of mathjax(latex) formula containing backslash.

Thanks

7
  • Do you mean String s = r"Hello \n World"; ? Commented Jun 8, 2020 at 20:58
  • Yes. ho to do that programmatically ? Commented Jun 8, 2020 at 21:00
  • So you gets a String from some REST API which contains e.g. the newline character and wants to convert it to the text "\n" instead? Commented Jun 8, 2020 at 21:01
  • 2
    The backslash should not influence the data you get from the REST API. It is only used when Dart compiles a String into a String object in code. So if you e.g. read a String from a file containing the letters "\n" it will not be seen as a newline character but instead as the letters "\n". Commented Jun 8, 2020 at 21:05
  • exactly, i get string containing backslash(\). when i print it or show(in flutter_tex) backslash is omitted automatically. Commented Jun 8, 2020 at 21:05

1 Answer 1

3

You are asking for a way to escape newlines (and possibly other control characters) in a string value.

There is no general way to do that for Dart strings in the platform libraries, but in most cases, using jsonEncode is an adequate substitute.

So, given your string containing a newline, you can convert it to a string containing \n (a backslash and an n) as var escapedString = jsonEncode(string);. The result is also wrapped in double-quotes because it really is a JSON string literal. If you don't want that, you can drop the first and last character: escapedString = escapedString.substring(1, escapedString.length - 1);.

Alternatively, if you only care about newlines, you can just replace them yourself:

var myString = string.replaceAll("\n", r"\n");
1
  • Thanks, your answer save me a lot of time.
    – sitatech
    Commented Dec 30, 2021 at 17:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.