First, you need to find the div object in the document. Use the
document.getElementById() method to do this:
obj = document.getElementById('foo');
Then, you need to get the contents of the div as a string. Use the
innerHTML property to do this:
text = obj.innerHTML;
If you look in the JavaScript reference, you'll see that the String
object has a method called split(). This breaks a string into pieces
and returns these pieces in an array. We'll need to split the contents
of the div by the newline character (\n) as follows:
lines = text.split("\n");
Note: there may be carriage return / line feed problems depending on
whether you're in a Unix, Windows or Mac environment. If the file was
created on Windows, you'll probably need to split by "\r\n".
This returns an array of each line, which you can then loop through,
and compose a new string containing the <a> tags and a <br> at the
end:
for (i=0; i<lines.length; i++)
{
newHTML = newHTML + '<a href="'+lines[i]+'">'+lines[i]+'</a><br>';
}
Lastly, set the innerHTML property of the div to the new string we've
made:
obj.innerHTML = newHTML;
I've included a sample script below.
Additional Links:
Netscape's DevEdge JavaScript Reference
http://developer.netscape.com/docs/manuals/communicator/jsref/
JavaScript Reference for String.split()
http://developer.netscape.com/docs/manuals/communicator/jsref/corea2.htm#1012977
Search Strategy:
javascript reference
://www.google.com/search?q=javascript+reference
<html>
<head>
<title>JavaScript: Using String.split()</title>
</head>
<body>
<div id="foo">
http://www.salon.com/
http://developer.netscape.com/
http://www.iol.co.za/
</div>
<br>
<a href="javascript:Reformat('foo');">Reformat!</a>
<script language="JavaScript1.2" type="text/javascript">
function Reformat(divid)
{
var obj = document.getElementById(divid);
var text = obj.innerHTML;
var newHTML = "";
lines = text.split("\n");
for (i=0; i<lines.length; i++)
{
newHTML = newHTML + '<a href="'+lines[i]+'">'+lines[i]+'</a><br>';
}
obj.innerHTML = newHTML;
}
</script>
</body>
</html> |