HTML строка удаляет лишние пробелы с помощью javascript

1

Привет, У меня есть HTML-строка, например

"     <div>       <p>You have received an alert from         project <span class="fields"          field="template.variable.ProjectName">          Project Name</span>        <br />       </p>        <p>        <span          field="template.variable.AlertName"          class="fields">Alert Name</span> <span          field="template.variable.AlertName"          class="fields">Alert Name</span> <span          field="template.variable.AlertName"          class="fields">Alert Name</span>        <br />       </p>        <p>Follow these steps to access the      alert:</p>        <ol>         <li>Log into your  for          Contract Management project         at <span            field="template.variable.AlertProjectLink"            class="fields">Alert Project Link</span></li>          <li>If necessary, enter your email address and the password          that you created when you completed your         registration.</li>          <li>Go to the Alerts tab to see your          unread alerts and         access links to the documents.</li>      </ol>        <p>        <span class="fields"          field="template.variable.AlertDocumentList">          Alert Document List</span></p>        <p>Please do not reply        to this message</p>        <p>.Space2 space gaurav Replies are        routed to an unmonitored       mailbox.</p>        <p>If you        would like additional assistance, please contact       Merrill        Technical Support, available 24 hours a day, seven       days a      week.</p>        <p>        <span class="template"          field="template.variable.ImportTemplate"          template="template.types.TechSupportContactInformation">          Tech Support Contact Information</span> test</p>        <p>Testing is going on</p>     </div>   "

Мне нужно заменить все последовательные пробелы одним пробелом, но не внутри тегов. Как вы можете видеть, что у меня есть <span field ="template.variable.AlertName" class="fields"> Alert Name</span>

Мне нужно <span field="template.variable.AlertName" class="fields">Alert Name</span>

Как вы можете видеть, я не хочу касаться пробелов атрибутов тега HTML.

Любая помощь будет высоко оценена Спасибо.

* Только для JAVASCRIPT

  • 0
    использовать trim () - w3schools.com/jsref/jsref_trim_string.asp
  • 0
    @BalajMarius, который не будет работать
Показать ещё 2 комментария
Теги:
string
replace
space

1 ответ

3
Лучший ответ

Использовать регулярное выражение

/(<.*?>)|\s+/g

с replace.

Регулярное выражение будет соответствовать

  1. (<.*?>): HTML-тег и добавьте его в первую группу захвата (вместо $1)
  2. | : ИЛИ в регулярном выражении
  3. \s+: или одно или несколько пробелов

Взамен проверьте, является ли это HTML-тегом else, замените лишние пробелы.

$1 - первая захваченная группа, т.е. Тег HTML. Если тег присутствует, то ничего не делайте, иначе удалите лишние пробелы.

var html = '     <div>       <p>You have received an alert from         project <span class="fields"          field="template.variable.ProjectName">          Project Name</span>        <br />       </p>        <p>        <span          field="template.variable.AlertName"          class="fields">Alert Name</span> <span          field="template.variable.AlertName"          class="fields">Alert Name</span> <span          field="template.variable.AlertName"          class="fields">Alert Name</span>        <br />       </p>        <p>Follow these steps to access the      alert:</p>        <ol>         <li>Log into your  for          Contract Management project         at <span            field="template.variable.AlertProjectLink"            class="fields">Alert Project Link</span></li>          <li>If necessary, enter your email address and the password          that you created when you completed your         registration.</li>          <li>Go to the Alerts tab to see your          unread alerts and         access links to the documents.</li>      </ol>        <p>        <span class="fields"          field="template.variable.AlertDocumentList">          Alert Document List</span></p>        <p>Please do not reply        to this message</p>        <p>.Space2 space gaurav Replies are        routed to an unmonitored       mailbox.</p>        <p>If you        would like additional assistance, please contact       Merrill        Technical Support, available 24 hours a day, seven       days a      week.</p>        <p>        <span class="template"          field="template.variable.ImportTemplate"          template="template.types.TechSupportContactInformation">          Tech Support Contact Information</span> test</p>        <p>Testing is going on</p>     </div>   ';

var res = html.replace(/(<.*?>)|\s+/g, (m, $1) => $1 ? $1 : ' ');
console.log(res);
  • 0
    Работает нормально Спасибо за ваш ответ, но не могли бы вы объяснить это мне
  • 0
    между тегами `<div> <p> у вас есть несколько лишних пробелов
Показать ещё 2 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню