首页 > 解决方案 > 去掉 \r\n\r\n 剩下的地方和指定标签 ul、li 前后

问题描述

我想删除\r\n\r\nif 多次发生,所以它会\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

我想在下面实现

  1. 有时 str 以多个开头\r\n并以相同结尾,所以我想删除所有这些。
  2. 介于 str 之间的哪个\r\n\r\n 想让它们保持为 single \r\n。例如 - course of action.\r\n\r\nThat’s OK — just because you
  3. 然后 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

在此处输入图像描述

标签: javascriptregex

解决方案


您可以使用

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>属性的两端删除所有空格。

推荐阅读