首页 > 解决方案 > 如何更换

 
使用 javascript 的空间?

问题描述

在正文中搜索所有实例<div>&nbsp;<br></div>并使用 JavaScript 替换为空格

标签: javascripthtmlregexreplace

解决方案


只需对元素使用String.replace()方法即可。.textContent

你并不完全清楚是否div应该更换整个或只是&nbsp;它的内部。以下是处理两者的示例:

仅替换&nbsp;

// 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;", " "); });
<div>&nbsp;<br></div>
<div>&nbsp;<br></div>
<div>&nbsp;<br></div>
<div>&nbsp;<br></div>

替换整个div

let el = document.getElementById("elementToSearch");

// Just replace all occurences of the element with a space
el.innerHTML = el.textContent.replace("<div>&nbsp;<br></div>", " ");
/* 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; }
<div id="elementToSearch">
  <div>&nbsp;<br></div>
  <div>&nbsp;<br></div>
  <div>&nbsp;<br></div>
  <div>&nbsp;<br></div>
</div>


推荐阅读