Convert \r\n characters to new line in Ionic 3

别来无恙 提交于 2019-12-08 13:16:53

问题


I want to be able to convert \r\n characters in a string to new lines

Example John is waiting now.\r\nCan we tell you about him. \r\nHe is a great person

Converted to

John is waiting now.

Can we tell you about him.

He is a great person

Tried this but to no avail

nl2br(text: string) {
    return text.replace(new RegExp('\r?\n','g'), '<br />');
}

回答1:


I think the problem might be due to the fact that your \r\n characters might be visible because they are "over escaped".

Furthermore I don't know exactly the context your replace has to be performed but I don't think you have to replace them by a <br/>

You could thus do something silly like

nl2br(text: string) {
    return text.replace('\\r\\n', '\n');
   //or return text.replace('\\r\\n', '<br/>') if it is really what you need
}

Note also that if you have a mix of escaped \n and \r, you can

nl2br(text: string) {
    return text.replace(/\\r\\n|\\r|\\n/gi, '\n');
   //or ...'<br/>');
}



回答2:


\n will show as line break if you apply below style to the element:

white-space: pre-wrap


来源:https://stackoverflow.com/questions/47163278/convert-r-n-characters-to-new-line-in-ionic-3

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