Link to home
Create AccountLog in
Avatar of nhacker

asked on

Parse URL with JavaScript

I am looking to parse part of a URL and store that part as a variable.  The URL entered will look like this:

ie., where '123456' is not constant.

Note: '123456' is not a real directory. This script will serve as a way for a client to enter their event id after our domain name and this script will then redirect them over to their client section which is represented by a more complicated url structure and would be hard to memorize.

What I am looking for is the contents after the first '/' and up to the next '/' if one exists but not including either '/' in the variable.  Then I would like for the contents of this parse to be stored in a variable called, say 'var1'

I will call this variable back via PHP Echo
<a href="<?php echo $var1?>"
Avatar of hielo
Flag of Wallis and Futuna image

Try this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="">
<script type="text/javascript"><!--
function getNumber()
	var hostname=location.hostname;
	var uri = location.href;
	uri = uri.replace(/^\s*https?[:][\/][\/]/i,"");
	uri = uri.replace(hostname,""); 
return uri[1];
function init()
	alert("The value extracted is: " + document.getElementById("uri").value);
	<input type="hidden" id="uri" name="var" value=""/>

Open in new window

Avatar of nhacker


ok. let me try this..
Avatar of nhacker


ok.  so the variable I am calling is 'uri' correct?

so - ran into a wall now.. what if nothing is entered?  do we need to construct an if-then statement

IF 'uri' contains nothing
THEN redirect to URL = "
ELSE redurect to URL = "<?php echo $uri?>

I hope this makes sense, in other words, we need to account for both situations where something is entered as and

Here is an example of this operation:
From my last post, instead of:
return uri[1] ;

you need:
return (uri[1] || "");

which basically sets the hidden field to an empty string. The redirection is something that you need to account for else where, but wherever you are doing this, if the hidden fields is empty, then you don't do anything.
Avatar of nhacker


getting an error on line 1

uploaded here:

Avatar of hielo
Flag of Wallis and Futuna image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of nhacker


ah.. got it... it is working correctly now....