newbie-shame
newbie-shame

Reputation: 243

If condition for redirection in jquery?

Edit...

Someone suggested I do it differently... If I were to use .htaccess, would this work?

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^chapter http://mysite.com/chapter/1

I'm just using basic javascript here, but I wanted to find out if there's a way to add it to my jquery file so that the redirection will happen if the path matches something specific?

Right now, I'm using:

<script type="text/javascript">window.location.replace("/chapter/1");</script>

I'd like that to only occur if the user goes to http://mysite.com/chapter.

I'm not altogether clear on how to get the path using jquery and do a pattern match?

Upvotes: 0

Views: 1770

Answers (2)

Keyne Viana
Keyne Viana

Reputation: 6202

$(document).ready(function(){

  if(window.location.href.match(/^.*\/chapter\/?$/)){
    window.location.replace("/chapter/1");
  }

});

See this question: How can I use JavaScript to match a string inside the current URL of the window I am in?

You can use the same regex in the htaccess file...

Upvotes: 0

SLaks
SLaks

Reputation: 887215

jQuery is a Javascript library which helps you manipulate DOM elements.
Since you're not manipulating DOM elements, jQuery won't do you any good.

You can use the location.href property:

if (location.href === '...')
    location.replace("/chapter/1");

Or,

if (/regex pattern/.test(location.href))
    location.replace("/chapter/1");

However, you should probably do this on the server instead.

Upvotes: 1

Related Questions