Extracting domain name from URL.
Example:
URL: http://www3.braingia.org
Domain Name: braingia.org
JavaScript:
var myString = "http://www3.braingia.org";
var myRegex = /http:\/\/\w+\.(.*)/;
var results = myRegex.exec(myString);
alert(results[1]);
Regular Expression:
/http:\/\/\w+\.(.*)/
The Idea:
What's inside of ( ) will be extracted.
Here's how it works.
http: looks for http:
\/\/ looks for //
Note that \(back slash) is an escape charactor
\w looks for any numaric charactor
+ makes it continue until it find non-numaric charactor
Note that /w+ doesn't mean “w”!
\. looks for . Now, it came up to the beginning of braingia.org
.* means match any character, and any and all of the previous charactors
And finally, ( ) extracts what parsed by .*
Posted below are the files just do that
HTML File (index.html)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel ="stylesheet" type = "text/css" href = "style.css">
<script type ="text/javascript" src ="extractDomain.js"></script>
</head>
<body>
<div id="wrapper">
<div id ="innerWrapper">
<h2>JavaScript: Learning Regular Expression</h2>
<div id="ex">
<p>Using RegExp object, extract domain name from URL</p>
<p>In this example, it extracts
<span class = "hilight">braingia.org</span>
from <span class ="hilight"> http:\\www.braingia.org</span>
</p>
</div>
</div>
</div>
</body>
</html>
CSS File (style.css)
body {
text-align:center;
font-family:"arial",verdana,sans-serif;
color: gray;
background-color: #f2f2f2;
}
#wrapper{
margin: 0 auto;
width: 900px;
text-align: left;
background: white;
}
#innerWrapper{
margin-left: 20px;
}
#ex{
color: gray;
}
.hilight{
color: orangered;
}
JavaScript File (extractDomain.js)
var myString = "http://www3.braingia.org";
var myRegex = /http:\/\/\w+\.(.*)/;
var results = myRegex.exec(myString);
alert(results[1]);
No comments:
Post a Comment