views:

66

answers:

2

My page's url is rewritten like so,

www.test-me.com/book-cat-white.HTML

  • book is book.php
  • cat is animal=cat
  • white is color=white

The original URL is

www.test-me.com/book.php?animal=cat&color=white

With PHP, I can get the values using $_GET, e.g. $_GET['animal']. How can I do the same in JavaScript? Is there a variable I can access that will return the query string?

A: 

You can query the GET string, but only the "public", rewritten one because that's what the browser sees.

If you need the internal, processed, un-rewritten parameters, I would recommend writing them out in the head from within PHP:

<script type="text/javascript">
query_animal = "<?php echo htmlspecialchars($_GET["animal"]); ?>";
query_color = "<?php echo htmlspecialchars($_GET["color"]); ?>";

</script>
Pekka
PHP 5.2+ you could just do `var $_GET = <?php echo json_encode($_GET, JSON_FORCE_OBJECT) ?>;`
gnarf
@gnarf nice idea!
Pekka
+1  A: 

You can use window.location and its properties however, this only points to http://WWW.test-me.com/book-cat-white.HTML -- The server side rewritten GET parameters will not be available to you.

You could try:

var match = window.location.pathname.match(/\/book-([^-]+)-([^-]+).html$/i);
// for your example - match contains: ["/book-cat-white.HTML", "cat", "white"]

A little further explanation of the Regular Expression:

/         # Start Expression
 \/book-   # Match '/book-'
 (         # Start Capture Group 1
  [^-]+     # Match any character other than '-' 1 or more times
 )         # End Capture Group 1
 -         # Match '-'
 (         # Start Capture Group 2
  [^-]+     # Match any character other than '-' 1 or more times
 )         # End Capture Group 2
 .html     # Match '.html'
 $         # Match the end of the string
/i        # End Expression - Case insensitive flag
gnarf
but this cat-white.html is not static ,this is dynamic...some time URL may be.... dog-brown.html
Bharanikumar
@Bharanikumar - yes, if the URL matches the RegExp... I.E. is `/book-dog-brown.html` then `match[1]` will be `dog` and `match[2]` will be `brown`
gnarf