Reputation: 3166
i'm just starting to learn jquery and i wanted to know if i'm doing it right. here is my code
var images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg','6.jpg', '7.jpg', '8.jpg', '9.jpg'];
if (window.location == 'http://localhost:81/ci/login') {
$('body').css('background-image', 'url("public/images/login_4.jpg")');
} else if(window.location == 'http://localhost:81/ci/index.php/login') {
$('body').css('background-image', 'url("../public/images/login_4.jpg")');
}else {
$('body').css({'background-image': 'url(public/images/' + images[Math.floor(Math.random() * images.length)] + ')'});
}
what the first block does is check if the location is the same as the given string
the problem with that is that if the url looks like this
http://localhost:81/ci/login?
or http://localhost:81/ci/login#
the code fails... I know there is a regex solution for that. What do you think fellas?
Upvotes: 1
Views: 124
Reputation: 6739
RegEx is inefficient and should be avoided for simple cases like this.
Try this instead:
if (window.location.href.indexOf('http://localhost:81/ci/login') == 0) {
...
} ...
If you insist on using a regex (certainly a handy tool to start learning) you can do the same thing like so:
if (/^http:\/\/localhost:81\/ci\/login/.test(window.location.href)) {
...
} ...
The caret ^ symbol marks the start of the string being matched - without that, this test would be true even if the pattern appeared in the middle of a string. Since the slashes mark the start and end of the regex, all slashes in the pattern must be escaped.
Upvotes: 1
Reputation: 11734
You don't need any regex for this, you can just use indexOf()
if(window.location.href.indexOf('http://localhost:81/ci/login') != -1)
{....}
else if(window.location.href.indexOf('http://localhost:81/ci/index.php/login' != -1)
{....}
Or better yet, combine them into this for more portable code:
if(window.location.href.indexOf('login') != -1)
Upvotes: 2