Borrowing from Michael Jasper's and Jon Hendershot's solutions, I offer the following:
$('address').each(function() {
var text = $(this).text();
var q = $.trim(text).replace(/\r?\n/, ',').replace(/\s+/g, ' ');
var link = '<a href="http://maps.google.com/maps?q=' + encodeURIComponent(q) + '" target="_blank"></a>';
return $(this).wrapInner(link);
});
This solution offers the following benefits over solutions previously offered:
- It will not remove HTML tags (e.g.
<br>
tags) within <address>
, so formatting is preserved
- It properly encodes the URL
- It squashes extra spaces so that the generated URL is shorter and cleaner and human-readable after encoding
- It produces valid markup (Mr.Hendershot's solution creates
<a><address></address></a>
which is invalid because block-level elements such as <address>
are not permitted within inline elements such as <a>
.
Caveat: If your <address>
tag contains block-level elements like <p>
or <div>
, then this JavaScript code will produce in invalid markup (because the <a>
tag will contain those block-level elements). But if you're just doing stuff like this:
<address>
The White House
<br>
1600 Pennsylvania Ave NW
<br>
Washington, D.C. 20500
</address>
Then it'll work just fine.