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

标签 javascript regex

javascript 如何预匹配 html 中的第一个词和最后一个词?

例如,在下面的句子中,我想要获取单词 Theunderway。谢谢。

<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/

相关文章:

java - 在 ";"上拆分 Java 中的字符串,但不在 "\\;"上拆分

javascript - 在 Google CSE 中隐藏优化选项卡?

javascript - jQuery 多步骤表单 : disable next button when fields unchecked

javascript - 将数据从父窗口传递到子窗口

javascript - 需要 ng-pattern 的正则表达式,该表达式应该是浮点型且始终大于 0,但不应允许 0

python - 在 Python 中使用正则表达式匹配区分大小写的 unicode 字符串

android - 在 SQLite 中搜索时排除 HTML 标签和一些 UNICODE 字符

正则表达式:删除里面有大括号的 <p></p> 段落

javascript - Backbone JS 和 JQuery 插件架构在 Mini Photoshop 项目中一起使用

javascript - 通过垂直进入制作 Div 容器负载