Java Reference
In-Depth Information
alert(resultsArray[index]);
}
}
This would result in three alert boxes containing the numbers 2012 , 2013 , and 2014 .
Splitting htML
trY it out
In this example, you want to take a string of HTML and split it into its component parts. For example,
you want the HTML <p>Hello</p> to become an array, with the elements having the following contents:
<p>
Hello
</p>
<!DOCTYPE html>
 
<html lang="en">
<head>
<title>Chapter 6, Example 5</title>
</head>
<body>
<div id="output"></div>
<script>
var html = "<h2>Hello World!</h2>" +
"<p>We love JavaScript!</p>";
 
var regex = /<[^>\r\n]+>|[^<>\r\n]+/g;
var results = html.match(regex);
 
document.getElementById("output").innerText = results.join("\r\n");
</script>
</body>
</html>
Save this file as ch6 _ example5.html . When you load the page into your browser you'll see that the
string of HTML is split, with each element's tags and content displayed on separate lines, as shown in
Figure 6-10.
Once again, the code that makes all of this work consists of just a few lines. You first create a RegExp
object and initialize it to your regular expression:
var regex = /<[^>\r\n]+>|[^<>\r\n]+/g;
Let's break it down to see what pattern you're trying to match. First, note that the pattern is broken
up by an alternation symbol: | . This means that you want the pattern on the left or the right of this
symbol. Look at these patterns separately. On the left, you have the following:
The pattern must start with a < .
In [^>\r\n]+ , you specify that you want one or more of any character except the > or a \r
(carriage return) or a \n (linefeed).
> specifies that the pattern must end with a > .
Search WWH ::




Custom Search