获取元素文本中的第一个和最后一个单词

时间:2011-09-24 14:53:31

标签: javascript html dom

在JavaScript中,如何从元素的文本中获取第一个和最后一个单词?

例如:

<div class="content">this is a test</div>// output 'this' 'test'
<p>This is another test</p>// output 'this' 'test'

我该怎么做?我不确定如何使用RegExp来匹配它们。

4 个答案:

答案 0 :(得分:1)

您应该尽量避免使用正则表达式解析html。看看这个SO答案RegEx match open tags except XHTML self-contained tags

您可以使用此正则表达式

var x = '<p>test test1</p>'.replace(/(<[^>]*>)/g,'').split(' ')

x [0]将是第一个字,x [x.length-1]将是最后一个元素

答案 1 :(得分:0)

您可以在Javascript

中使用以下正则表达式与replace()结合使用
/([a-z]+) .* ([a-z]+)/i

工作演示:http://jsfiddle.net/e8yZd/2/

答案 2 :(得分:0)

getFirstAndLastWords("this is a test"); // Outputs: "this test"

function getFirstAndLastWords(text) {
  var text_arr = text.split(" ");
  return text_arr[0] + " " + text_arr[text_arr.length-1];
}

答案 3 :(得分:0)

使用元素比使用html更好。

var text=(element.textContent || element.innerText).match(/\w+/g) ||[];
alert(text[0]+'\n'+text.pop());