问题
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