Make all external links open in a new window

If we want to make all links on our site that pointed to external domains open in a new window. This is fairly trivial if we’re in total control of the entire markup, as shown:

<a href="http://external.com" target="_blank">Some External Site</a>

That’s all well and good, but what if we’re running a Content Management System or a wiki, where end users will be able to add content, and we can’t rely on them to add the target="_blank" to all external links? First, let’s try and determine what we want; we want all links whose href attribute begins with http:// to open in a new window (which we have determined can be done by setting the target attribute to _blank).
We can use the techniques we’ve learned in this section to do this concisely, as follows:

$("a[href^=http://]").attr("target","_blank");

First, we select all links with an href attribute starting with http:// (which indicates
that the reference is external). Then, we set its target attribute to _blank.
Mission accomplished with a single line of jQuery code!