如何用空格替换<div> <br/> </div>和空格?

时间:2018-06-13 18:56:45

标签: javascript html regex replace

在正文中搜索<div>&nbsp;<br></div>的所有实例,并使用JavaScript

替换为空格

2 个答案:

答案 0 :(得分:2)

只需在.textContent元素上使用 String.replace() 方法。

您是否应该完全清楚整个div是否应该被替换,或者只是替换它内部的&nbsp;。以下是处理两者的示例:

只替换&nbsp;

&#13;
&#13;
// Get all the elements that need work into an array
let elements = Array.prototype.slice.call(document.querySelectorAll("div"));

// Loop over the array and replace the HTML entity with a space char.
elements.forEach((el) => { el.textContent = el.textContent.replace("&nbsp;", " "); });
&#13;
<div>&nbsp;<br></div>
<div>&nbsp;<br></div>
<div>&nbsp;<br></div>
<div>&nbsp;<br></div>
&#13;
&#13;
&#13;

替换整个div

&#13;
&#13;
let el = document.getElementById("elementToSearch");

// Just replace all occurences of the element with a space
el.innerHTML = el.textContent.replace("<div>&nbsp;<br></div>", " ");
&#13;
/* You won't see this style applied anywhere because 
   all the div elements have been removed*/
#elementToSearch div { width:400px; height:100px; background-color:yellow; }
&#13;
<div id="elementToSearch">
  <div>&nbsp;<br></div>
  <div>&nbsp;<br></div>
  <div>&nbsp;<br></div>
  <div>&nbsp;<br></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

此示例使用直接Javascript。

&#13;
&#13;
myDivList = document.getElementsByTagName("div");
for (var i = 0; i < myDivList.length; i++) {
  if (myDivList[i].innerHTML == "&nbsp;<br>") {
    myDivList[i].innerHTML = "New value.";
  }
}
&#13;
<div>&nbsp;<br></div>
<div>Not this one.</div>
<div>Not this one.</div>
<div>&nbsp;<br></div>
&#13;
&#13;
&#13;