[英]javascript replace tag-regex undepend html-attributes
我一直在嘗試替換這些字符串:
<title id="hello">my title </title>
<title >my title </title>
<title id="hello" class="blue">my title </title>
我需要正則表達式,它替換標題標簽之間的文本,不依賴屬性。 遺憾的是,我只得到了這個正則表達式的第二個例子:
str.replace(/<\/?title>/g,'')
有任何想法嗎?
最好避免使用正則表達式來解析 HTML。
var html = `<title id="hello">my title </title> <title >my title </title> <title id="hello" class="blue">my title </title>`; // generate a temporary div elementt var temp = document.createElement('div'); // set its html content as the string temp.innerHTML = html; //do the rest here // get all title tags Array.from(temp.getElementsByTagName('title')) // iterate over the title tag and do the necessary chenges .forEach(function(ele) { ele.innerHTML = 'new content' }) // get back the updated html content from dom element console.log(temp.innerHTML);
前 NodeJS 參考: Node.js 上的 HTML-parser
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.