1

Hey, i think this is an easy question. I have a URL and i want to set one of the directories in a variable.

URL:
http://www.domainname.com/Irving/For-Sale/Used/Dodge/Ram-1500/2009--Black-Truck/4691335/

var usedInventory = _____

I need a variable that equals "Used"

Let me know if you have any questions!

Thanks!

3
  • I don't quite follow. You are trying to find the value of the 3rd level directory from the URL? Commented Nov 2, 2010 at 14:14
  • Yes, you are correct...sorry if i wasn't very clear! :) Commented Nov 2, 2010 at 14:15
  • is it always the 3rd level that you want? Commented Nov 2, 2010 at 14:17

3 Answers 3

4
js> var url = 'http://www.domainname.com/Irving/For-Sale/Used/Dodge/Ram-1500/2009--Black-Truck/4691335/';
js> url.split('/')[5]
Used

In a browser environment, use location.href instead of url. You don't even have to involve jQuery for that btw.

var urlParts = location.href.split('/');
var yourField = urlParts[5];
Sign up to request clarification or add additional context in comments.

1 Comment

+1. You can also use window.location.pathname to skip the irrelevant host name parts and just split up the path parameters. In this case, the part required is [2].
1

I would use PHP to grab the variable from the URL. Since you're using mod_rewrite I'm assuming the variable is named "used". I'm also assuming that you're working in an environment that is PHP.

<?php $used = $_GET['used']; ?>

var usedInventory = <?php echo $used; ?>

2 Comments

You should at use $used = isset($_GET['used']) ? $_GET['used']: ''; to ensure no notice is thrown if the variable is not set.
Pretty URLs doesn't mean mod_rewrite (and subsequently doesn't mean PHP). Apache is only one of many web server engines that allows URL rewriting, and other server side technologies can be used with Apache.
0
mystring = "http://www.domainname.com/Irving/For-Sale/Used/Dodge/Ram-1500/2009--Black-Truck/4691335/";
if (mystring.match(/Used/)) {
    alert("Used");
}

1 Comment

He wants to extract it, not check if it contains it - especially not at a random position...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.