How to convert string to raw string in dart

谁都会走 提交于 2021-01-29 16:37:08

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/62270974/how-to-convert-string-to-raw-string-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!