[英]How can I match/capture the just the opening tag of the outerHTML of an element
我正在嘗試僅捕獲HTML元素的開始標記。 我正在使用element.outerHTML來獲取要使用的文本字符串。 當開始標記后有新行時,它將起作用:
var div = document.querySelector('div'); console.log( div.outerHTML.match(/^<(.*)>/)[1] );
<div id="awesomeID" class="one two three four"> </div>
但是,當元素是1襯線時,它會斷裂並一直捕獲到結束標記的結尾:
var div = document.querySelector('div'); console.log( div.outerHTML.match(/^<(.*)>/)[1] );
<div id="awesomeID" class="one two three four"></div>
我如何才能僅捕獲開始標簽?
使用惰性限定符*?
而不是貪婪的一個*
。
var div = document.querySelector('div'); console.log( div.outerHTML.match(/^<(.*?)>/)[1] );
<div id="awesomeID" class="one two three four"></div>
貪婪限定符與盡可能多的匹配項匹配,因此它在最后一個可能的匹配項處停止。 在您的示例中,它停在最后一個>
。
盡管惰性限定符與盡可能少的匹配項匹配,所以它在第一個可能的匹配項處停止。 在您的示例中,它停在第一個>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.