TheDefiant89
TheDefiant89

Reputation: 35

Using regex in javascript to select only text between tags

I've searched and searched but can't seem to find the answer I need. I'm still wrapping my head around the whole regex thing don't know enough to solve this problem, which seems far to simple.

I have a string "<a href="#">London<span>35.2miles</span></a>"

I need to chop everything apart from "London", but everything I try results in "London<span>35.2miles</span>" I cannot seem to get rid of the span tags and text, as well as the a tags.

Upvotes: 0

Views: 2314

Answers (2)

Esailija
Esailija

Reputation: 140236

var root = document.createElement("div");
root.innerHTML = '<a href="#">London<span>35.2miles</span></a>';
alert( root.firstChild.firstChild.nodeValue );

Upvotes: 3

Matt
Matt

Reputation: 75327

The following regular expression should work;

/>([^<]*)/

It matches anything from the first > until it hits another <

You can combine this with the match() method, to end up with something like this;

var matches = '<a href="#">London<span>35.2miles</span></a>'.match(/>([^<]*)/);

if (matches) { // "null" if no matches, array if there was.
    var london = matches[1];
}

Upvotes: 0

Related Questions