[英]Javascript for extracting anchor text from anchor tag
在下面需要幫助。
在javascript中,需要傳遞輸入
如:
str="<a href=www.google.com>Google</a>"; // this is for example actual input vary
// str is passed as parameter for javascript function
輸出應檢索為“ Google”。
我在Java中有正則表達式,並且在其中工作正常。
String regex = "< a [ ^ > ] * > ( . * ? ) < / a > ";
Pattern p = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
但在javascript中無法正常工作。
我該如何用Javascript做到這一點。 誰能為我提供有關JavaScript實現的幫助。
我不認為您要為此使用Regex。 您可以這樣簡單地嘗試:-
<a id="myLink" href="http://www.google.com">Google</a>
var anchor = document.getElementById("myLink");
alert(anchor.getAttribute("href")); // Extract link
alert(anchor.innerHTML); // Extract Text
編輯:-(正如Patrick Evans正確評論的那樣)
var str = "<a href=www.google.com>Google</a>";
var str1 = document.createElement('str1');
str1.innerHTML = str;
alert(str1.textContent);
alert( str1.innerText);
從大家的建議中我得到了答案並為我工作
function extractText(){
var anchText = "<a href=www.google.com>Google</a>";
var str1 = document.createElement('str1');
str1.innerHTML = anchText;
alert("hi "+str1.innerText);
return anc;
}
謝謝大家的支持
只是初步了解一下,我可以更新一下,這是您在問題中添加了更多測試用例或詳細信息:
\w+="<.*>(.*)</.*>"
這與您提供的示例匹配,此外,是否:
特別是,如果您的html標記內有尖括號,則可能會打破此限制。
注意:使用html進行此操作是一個更好的主意,因為嘗試了其他答案,所以我只使用了正則表達式來回答,因為這是OP的要求。 對於OP,如果無需正則表達式即可執行此操作,請改為執行此操作。 您不應在可能的情況下嘗試使用javascript解析HTML,並且此正則表達式無法與完整的html解析器進行比較。
不需要正則表達式,只需使用DOMParser解析字符串並獲取元素,然后使用DOM對象的方法/屬性
var parser = new DOMParser();
var str='<a href='www.google.com'>Google</a>";
var dom = parser.parseFromString(str,"text/xml");
//From there use dom like you would use document
var atags = dom.getElementsByTagName("a");
console.log( atags[0].textContent );
//Or
var atag = dom.querySelector("a");
console.log( atag.textContent );
//Or
var atag = dom.childNodes[0];
console.log( atag.textContent );
IE 9以下版本不支持DOMParser。
好吧,如果您使用的是JQuery,這應該很容易。
我只是創建一個不可見的div並在其上呈現此anchor()。 之后,您可以簡單地選擇錨點並獲取其內部文本。
$('body').append('<div id="invisibleDiv" style="display:none;"></div>'); //create a new invisible div
$('#invisibleDiv').html(str); //Include yours "str" content on the invisible DIV
console.log($('a', '#invisibleDiv').html()); //And this should output the text of any anchor inside that invisible DIV.
請記住,要這樣做,必須在頁面上加載JQuery。
編輯:僅當您已經在項目上具有JQuery時使用,因為如下所述,因為這不應該是將整個庫包含在內的簡單原因。
假設您使用的是Java,請提供的代碼。
我建議您使用JSoup提取錨標記內的文本。
這是一個原因。 使用正則表達式解析HTML:為什么不呢?
String html = "<a href='www.google.com'>Google</a>";
Document doc = Jsoup.parse(html);
Element link = doc.select("a").first();
String linkHref = link.attr("href"); // "www.google.com"
String linkText = link.text(); // "Google""
String linkOuterH = link.outerHtml();
// "<a href='www.google.com'>Google</a>";
String linkInnerH = link.html(); // "<b>example</b>"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.