Как разрешить конфликт document.body.inner HTML .replace? - PullRequest
0 голосов
/ 09 апреля 2020

Я использую javascript, чтобы скрыть все между двумя html тегами комментариев, но когда я использую этот код на своей странице, некоторые другие javascript портятся. Мне нужна помощь, чтобы исправить мой код, чтобы он не конфликтовал с другими.

<!-- start html comment --> remove me <! -- end html comment -->


document.body.innerHTML = document.body.innerHTML.replace(/\<\!\-\- start html comment -\-\>((.|[\n|\r|\r\n])*?)\<\!\-\- end html comment -\-\>[\n|\r|\r\n]?(\s+)?/g, ""); 

Ответы [ 2 ]

0 голосов
/ 09 апреля 2020

Если в вашем примере есть дополнительное пространство:

<!-- start html comment --> remove me <! -- end html comment -->
//                              here ___^

Я удалил его в своем решении.

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

<!-- start html comment -->[^]+?<!-- end html comment -->\s*

Демонстрация и объяснение

Ваш код становится:

document.body.innerHTML = 
  document.body.innerHTML.replace(/<!-- start html comment -->[^]+?<!-- end html comment -->\s*/g, ""); 
0 голосов
/ 09 апреля 2020

Использование сокращенного кода из этой версии DOM для вопроса.

var page = document.getElementsByTagName("html")[0];
removeComments(page);
console.log(document.body.outerHTML);

function removeComments(curr_element) { // this is the recursive function
  // base case: node is a comment node
  if (curr_element.nodeName == "#comment" || curr_element.nodeType == 8) {
    // You need this OR because some browsers won't support either nodType or nodeName... I think...
    console.log(curr_element.data);
    curr_element.parentNode.removeChild(curr_element);
  }
  // recursive case: node is not a comment node
  else if (curr_element.childNodes.length > 0) {
    for (var i = 0; i < curr_element.childNodes.length; i++) {
      // adventures with recursion!
      removeComments(curr_element.childNodes[i]);
    }
  }
}
<UL>
<LI>1st<!-- HTML comment 1 --></LI>
<LI>2nd</LI><!-- HTML comment 2 -->
</UL>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...