Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

javascript - 如何将字符串中的所有换行符替换为 <br /> 标签?(How do I replace all line breaks in a string with <br /> tags?)

How can I read the line break from a value with JavaScript and replace all the line breaks with <br /> tags?(如何使用JavaScript从值读取换行符并将所有换行符替换为<br />标记?)

Example:(例:) A variable passed from PHP as below:(从PHP传递的变量如下:) "This is man. Man like dog. Man like to drink. Man is the king." I would like my result to look something like this after the JavaScript converts it:(我希望我的结果在JavaScript转换后看起来像这样:) "This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."   ask by Jin Yong translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will turn all returns into HTML(这会将所有退货转换为HTML)

str = str.replace(/(?: | | )/g, '<br>'); In case you wonder what ?: means.(如果您想知道什么?:的意思。) It is called a non-capturing group.(它称为非捕获组。) It means that group of regex within the parentheses won't be saved in memory to be referenced later.(这意味着括号内的正则表达式组不会保存在内存中,以后再引用。) You can check out these threads for more information:(您可以查看以下线程以获取更多信息:)
https://stackoverflow.com/a/11530881/5042169 https://stackoverflow.com/a/36524555/5042169(https://stackoverflow.com/a/11530881/5042169 https://stackoverflow.com/a/36524555/5042169)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...