在JavaScript中,如何从元素的文本中获取第一个和最后一个单词?
例如:
<div class="content">this is a test</div>// output 'this' 'test'
<p>This is another test</p>// output 'this' 'test'
我该怎么做?我不确定如何使用RegExp来匹配它们。
答案 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)
答案 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());