javascript 如何预匹配 html 中的第一个词和最后一个词?
例如,在下面的句子中,我想要获取单词 The
和 underway
。谢谢。
<p>The Stack Overflow 2011 community moderator election is underway</p>
//should consider the different html tags.
最佳答案
如果元素已经存在于文档中,则可以获取其文本内容,并根据""
进行拆分:
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
。如果没有单词,则 1st 将为空字符串 ""
,last 仍为 undefined
。
关于javascript - 如何使用javascript正则表达式,从html中获取第一个词和最后一个词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8068176/