fish man
fish man

Reputation: 2700

Get first and last word in element's text

In JavaScript, how can I get the first and last words from an element's text?

For example:

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

How can I do that? I am not sure how to use RegExp to match them.

Upvotes: 1

Views: 4204

Answers (4)

MisterGreen
MisterGreen

Reputation: 151

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];
}

Upvotes: 2

kennebec
kennebec

Reputation: 104780

Better with elements than html.

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

Upvotes: 0

Narendra Yadala
Narendra Yadala

Reputation: 9664

You should try to avoid parsing html with regex. Look at this SO answer RegEx match open tags except XHTML self-contained tags

You can use this regex

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

x[0] will be first word, x[x.length-1] will be last element

Upvotes: 1

Fad
Fad

Reputation: 9858

You can use the following regex with combined with replace() in Javascript

/([a-z]+) .* ([a-z]+)/i

Working demo: http://jsfiddle.net/e8yZd/2/

Upvotes: 0

Related Questions