cj333
cj333

Reputation: 2609

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?

for example, in the below sentence, I want get words The and underway. Thanks.

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

Upvotes: 1

Views: 5068

Answers (2)

Andy E
Andy E

Reputation: 344565

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. If there are no words, 1st will be an empty string, "" and last will still be undefined.

Upvotes: 4

Dennis
Dennis

Reputation: 32598

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

Upvotes: 4

Related Questions