如果要多次发生,我想删除\r\n\r\n
,所以它应该是\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,这打扰了我的UI。
第二,打扰<li>
和</li>
UI
我想实现以下目标
\r\n
开头,并以相同的结尾
所以我想删除所有这些。 \r\n\r\n
之间
希望将它们保持为单个\r\n
。例如-course of action.\r\n\r\nThat’s OK — just because you
。 <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
。答案 0 :(得分:1)
您可以使用
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>
和{{1} }甚至带有属性。