[英]Text component react-native - how to escape newline but allow /n to display by escaping it as //n
我正在研究Text react-native组件,为我的应用制作标签。 我希望能够将所有\\n
变成一个实际的换行符,但是如果我这样逃避它,则可以在我的Text组件中显示\\n
: \\\\n
我已经尝试了很多事情,但似乎无法使其正常工作,包括用尝试的转义配置(当前代码段)进行替换,replaceAll。
const textCustomSetter = (newValue, newComponent) => {
newComponent.properties.Text = newValue;
newComponent.properties.children = newValue.split('\\n').join('\n');
};
其中,textCustomSetter是Text组件的设计和运行时设置程序属性。
这样可以正确捕获\\n
并将其转换为换行符,但是将\\\\n
转换为\\
然后\\\\n
行。
只需replace
其replace
为正则表达式即可:
newValue.replace(/[^\\]\\n/g, "\n");
这是通过不匹配单个反斜杠,然后匹配文字\\n
(例如,反斜杠和n
,而不是换行符)并将其替换为换行符来实现的。
我相信我知道了。 这会将\\ n变成换行符,并将所有2个或更多斜杠后跟一个n的字符串减少到一个斜杠。 我知道这是一个非常具体的规范,但我想分享一下如何使它起作用。 感谢您的帮助,让我不再对正则表达式感到困惑!
现在,我只需要弄清楚使它在前端工作的语法。
const textCustomSetter = (newValue, newComponent) => {
newComponent.properties.Text = newValue;
//split on one or more slashes before an n, keep the delimiter
var arr = newValue.split(/(\\{1,}n)/g);
for (var i = 0; i < arr.length; i++) {
if (arr[i] == "\\n") {
//address the newline
arr[i] = "\n";
}
//everything else, gets one slash reduced
if (arr[i].match(/\\{2,}n/g)){
arr[i] = arr[i].substr(1);
}
}
newComponent.properties.children = arr;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.