PDA

View Full Version : I need help with some javascript:



thenextbesthang
10-06-2006, 05:09 PM
I am trying to replace [[x y z]]
with
<a href="http://en.wikipedia.org/wiki/x_y_z">x y z</a>".
, similarly i am trying to replace [[x#y]]
with
<a href="http://en.wikipedia.org/wiki/x#y">x#y</a>
-----
here is what I have so far:
<html>
<head>
<title>Project.Link</title>
</head>
<body>
<script type= "text/javascript">
var input = window.prompt("Enter Text Here");
for(i=0;i<=input.length;i++)
{
var openbrackets = input.indexOf("[[");
var closebrackets = input.indexOf("]]");
var linkstart = openbrackets+2;
var linkend = closebrackets--;
var link = input.substring(linkstart, linkend);
}
for (i=linkstart;i<=linkend;i++)
{
if (link.charAt(i) == " ")
{
var replace_ = link.replace(" ", "_");
}
}
for (i=0;i<=input.length;i++)
{
var replaceo = input.replace("[[", '<a href="http://en.wikipedia.org/wiki/'+replace_+'">');
var replacec = input.replace("]]", '</a>');
}
var sentence = replaceo.concat(link);
var tsentence= document.write(sentence.concat(replacec));
</script>
</body>
</html>

------

Can anyone help me? Where is my code wrong?!?!

Twey
10-06-2006, 08:06 PM
There's an easier way:
function wikify(str) {
return str.replace(/\[\[([^\]]+)\]\]/g, function() {
return '<a href="' + encodeURIComponent(arguments[1].replace(" ", "_")) + '">' + arguments[1] + "</a>";
});