0

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

but this cat-white.html is not static , this is dynamic...some time URL may be.... dog-brown.html
@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
0

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>

1 Comment

PHP 5.2+ you could just do var $_GET = <?php echo json_encode($_GET, JSON_FORCE_OBJECT) ?>;

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.