PDA

View Full Version : Need help with script



blm126
09-25-2005, 06:47 PM
I'm trying to write a script that can access a variable stored in the url. Like somefile.html?something=variable
Right now I've got a script that works but I would like to streamline it.

My current script is

<head>

<SCRIPT LANGUAGE="javascript">



function urlvar1()
{
var locate = window.location
document.locform.loc.value = locate
var loc = document.locform.loc.value
var start = loc.indexOf("=") + 1
var result = loc.substring(start)
return result
}

</SCRIPT>
<body>
<FORM NAME="locform">
<INPUT TYPE="hidden" NAME="loc">
</FORM>

<script type="text/javascript" language="javascript">


document.write(urlvar1())
</script>


</body>

It works,but I want to find a way to get rid of the form. Right now I'm using it to turn window.location property into a string. Does anyone know another way to turn the url into a string. I want all the code to go in the function urlvar1() so all you do is link to the script then call the function without the extra html.

Twey
09-25-2005, 07:12 PM
window.location.href is a string.

blm126
09-25-2005, 07:44 PM
Thanks I can't beleive I didn't know that. I even spent tweny minutes on google trying to find that.

Twey
09-25-2005, 08:22 PM
Heh, no problem.

mwinter
09-25-2005, 10:34 PM
function urlvar1()
{
var locate = window.location
document.locform.loc.value = locate
var loc = document.locform.loc.value
var start = loc.indexOf("=") + 1
var result = loc.substring(start)
return result
}So this rears its ugly head again, does it?

Someone else posted code very similar to that earlier this year after obtaining it from a very badly written article found on the Web. A better solution would use regular expressions (which I posted in that thread (http://www.dynamicdrive.com/forums/showthread.php?t=2428)), though something reliable but much bulkier could be written without them.


Does anyone know another way to turn the url into a string.The JavaScript 1.0 approach, which could have been used in the original article, would be concatenation with an empty string:


'' + locationbut the better approach (in my opinion) is using the String constructor/conversion function:


String(location)Of course, neither was ever necessary.

Mike