[英]how to use javascript regex, get first word and last word from html
javascript如何預備匹配html中的第一個單詞和最后一個單詞?
例如,在下面的句子中,我想得到單詞The
and underway
。 謝謝。
<p>The Stack Overflow 2011 community moderator election is underway</p>
//should consider the different html tags.
您不需要正則表達式:
var words = "The Stack Overflow 2011 community moderator election is underway".split(" "),
first = words[0],
last = words[words.length-1];
如果元素已經在文檔中,則可以獲取其文本內容並根據" "
拆分:
var text = "textContent" in document.body ? "textContent" : "innerText",
el = document.getElementById("myElement"),
arr = el[text].split(" "),
first = arr.shift(),
last = arr.pop();
alert("1st word is '"+first+"', last word is '"+last+"'.");
如果還不是元素,請使其成為一個:
var arr, first, last,
text = "textContent" in document.body ? "textContent" : "innerText",
html = "<p>The Stack Overflow 2011 community moderator election is underway</p>",
el = document.createElement("div");
el.innerHTML = html;
arr = el[text].split(" "),
first = arr.shift(),
last = arr.pop();
alert("1st word is '"+first+"', last word is '"+last+"'.");
注意:這並未考慮標點符號-您可能希望在分割之前使用簡單的正則表達式從字符串中刪除其中的一些標點符號。 另外,如果文本中只有一個單詞,則last
將是undefined
。 如果沒有單詞,則第一個將是一個空字符串, ""
,最后一個將仍然是undefined
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.