javascript - 去掉 \r\n\r\n 剩下的地方和指定标签 ul、li 前后
问题描述
我想删除\r\n\r\n
if 多次发生,所以它会\r\n\r\n
是\r\n
.
之后,如果\r\n
或\n
出现在 HTML 旁边<li>
,</li>
或者<ul></ul>
显示在附加图像中。
var str= "\r\n\r\nSometimes, fast food or a meal at your favorite eatery is the easiest course of action.\r\n\r\nThat’s OK — just because you’re eating out doesn’t mean your food has to be unhealthy.<h2>Ways to Eat Healthier at Restaurants</h2>\r\n<ol>\r\n \t<li>\r\n<h3>Choose healthier food options.</h3>\r\n</li>\r\n</ol>\r\nMany restaurants have healthy food options on the menu. Head straight for that section and avoid anything that’s breaded, fried, crispy, or buttered. Instead of fries as your side dish, choose veggies, fruit, or a salad. If you get a salad, ask that dressing come on the side and use it sparingly. \r\n<ol start=\"2\">\r\n \t<li>\r\n<h3>Control your portions.</h3> \r\n</li>\r\n</ol>\r\nMany restaurants serve giant portions. Save half your meal for lunch the next day. If you don’t trust yourself, ask your server for a to-go container when placing your food order. When your meal arrives at the table, pack up half of it immediately.\r\n<ol start=\"3\">\r\n \t<li>\r\n<h3>Eat slowly.</h3>\r\n</li>\r\n</ol>\r\n\r\n\r\n\r\n";
str = str.replace(/[\r\n]+/g, '').replace(/[\t]+/g, '') ;
和
str = str.replace(/[\r\n]+/g, '\n').replace(/[\t]+/g, '') ;
第一种情况是删除所有地方 \n 并且它扰乱了我的用户界面。二、打扰<li>
和</li>
UI
我想在下面实现
- 有时 str 以多个开头
\r\n
并以相同结尾,所以我想删除所有这些。 - 介于 str 之间的哪个
\r\n\r\n
想让它们保持为 single\r\n
。例如 -course of action.\r\n\r\nThat’s OK — just because you
。 - 然后 srt
<ol>\r\n \t<li>\r\n<h3>Choose healthier food options.</h3>\r\n</li>\r\n</ol>\r\n
(应该成为<ol><li><h3>Choose healthier food options.</h3></li></ol>
)或任何其他指定的标签应该删除\r\n
。
解决方案
您可以使用
s.trim().replace(/(\r?\n){2,}/g, '$1').replace(/\s*(<\/?(?:[ou]l|li)>)\s*/gi, '$1')
这将执行以下操作:
.trim()
- 从字符串的开头/结尾删除所有空格.replace(/(\r?\n){2,}/g, '$1')
- 将所有重复的连续换行符缩小为单个换行符.replace(/\s*(<\/?(?:[ou]l|li)>)\s*/gi, '$1')
<ul>
- 从,</ul>
,<ol>
,</ol>
,<li>
甚至</li>
属性的两端删除所有空格。
推荐阅读
- angular - Angular HttpModule - 隐藏浏览器的控制台错误消息状态!= 200
- apache-kafka - kafka数据日志目录下有哪些不同的日志
- function - .then() 方法在使用 ES5 语法时被忽略
- react-native - React Native:无法在 Genymotion 上模拟
- python - Heroku EOFError 仅适用于两行 python 代码
- python-3.x - Python/MatPlotLib:如何添加按钮以从串口绘制实时数据
- python - 安装 pip 包时出现“正则表达式构建失败”
- angular - 向ionic中动态创建的组件添加点击事件
- typescript - 如何在打字稿中读取打字稿文件(CSV)?
- apache-spark - 通过 Spark SQL 查询 Cassandra UDT