简体   繁体   English

如何使用javascript正则表达式,从html获取第一个单词和最后一个单词

[英]how to use javascript regex, get first word and last word from html

javascript how to preg match first word and last word from html? javascript如何预备匹配html中的第一个单词和最后一个单词?

for example, in the below sentence, I want get words The and underway . 例如,在下面的句子中,我想得到单词The and underway Thanks. 谢谢。

<p>The Stack Overflow 2011 community moderator election is underway</p>
//should consider the different html tags.

You don't need regular expressions: 您不需要正则表达式:

var words = "The Stack Overflow 2011 community moderator election is underway".split(" "),
    first = words[0],
    last = words[words.length-1];

If the element is already in the document, you can get its text content and split it based on " " : 如果元素已经在文档中,则可以获取其文本内容并根据" "拆分:

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+"'.");

If it's not already an element, make it one: 如果还不是元素,请使其成为一个:

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+"'.");  

Note: this doesn't take punctuation characters into account - you might want to remove some of them from the string with a simple regex before splitting. 注意:这并未考虑标点符号-您可能希望在分割之前使用简单的正则表达式从字符串中删除其中的一些标点符号。 Also, if there is only a single word in the text, last will be undefined . 另外,如果文本中只有一个单词,则last将是undefined If there are no words, 1st will be an empty string, "" and last will still be undefined . 如果没有单词,则第一个将是一个空字符串, "" ,最后一个将仍然是undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM