[英]Remove HTML tags and its contents from a string - Javascript
假設我有以下字符串: const test = "This is outside the HTML tag. <title>How to remove an HTML element using JavaScript?</title>";
我想刪除該字符串中所有 HTML 標簽中的內容。 我試過做test.replace(/(<([^>]+)>)/gi, '')
,但這只會刪除 HTML 標簽,而不是其中的所有內容。 我希望結果只會是“這在 HTML 標簽之外。”。
是否可以刪除字符串中的 HTML 標簽及其內容?
您可以通過在兩個正則表達式之間放置一個通配符來替換兩個元素之間的所有內容
const test = "This is outside the HTML tag. <title>How to remove an HTML element using JavaScript?</title>"; console.log(test.replace(/(<([^>]+)>).*(<([^>]+)>)/, ''))
與其嘗試通過正則表達式刪除 HTML 元素,不如使用以下方法創建和填充DOM 片段更直接:
let myDiv = document.createElement('div');
myDiv.innerHTML = test;
然后從中刪除<title>
元素,使用:
myDivTitle = myDiv.querySelector('title');
myDiv.removeChild(myDivTitle);
工作示例(一個元素):
const test = "This is outside the HTML tag. <title>How to remove an HTML element using JavaScript?</title>"; let myDiv = document.createElement('div'); myDiv.innerHTML = test; myDivTitle = myDiv.querySelector('title'); myDiv.removeChild(myDivTitle); const testAfter = myDiv.innerHTML; console.log(testAfter);
以上適用於一個元素( <title>
)但你說:
我想刪除該字符串中所有 HTML 標簽中的內容
所以讓我們嘗試一些更有野心的東西,使用:
myDiv.querySelectorAll('*')
工作示例(所有元素):
const test = "<title>How to remove an HTML element using JavaScript?</title> This is outside the HTML tag. <h1>Here we go...</h1> So is this. <p>This is going to save a lot of time trying to come up with regex patterns</p> This too."; let myDiv = document.createElement('div'); myDiv.innerHTML = test; myDivElements = myDiv.querySelectorAll('*'); for (myDivElement of myDivElements) { myDiv.removeChild(myDivElement); } const testAfter = myDiv.innerHTML; console.log(testAfter);
你應該這樣嘗試:
var html = "<p>Hello, <b>Frields</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, Frields
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.