Md Mahmudul Islam
Md Mahmudul Islam

Reputation: 2712

How to convert string to raw string in dart

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

Upvotes: 3

Views: 2330

Answers (1)

lrn
lrn

Reputation: 71623

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");

Upvotes: 3

Related Questions