Javascript: how to check if a url contains a word

I want to check if the URL in the browser contains the word "Desktop" (I am running the html file from the desktop). Its url is: "file: /// C: /Users/Joe/Desktop/TestAlert.html"

But a warning should appear, but this does not work.

Here is my code:

<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
    if(window.location.href.contains("Desktop") > -1) {
       alert("Alert: Desktop!");
    }
});
</script>
</head>
<body>
    <h1>Test001</h1>
</body>
</html>

I tested this in Firefox, Chrome and Internet Explorer. It would be very nice if someone can help me!

+4
source share
6 answers

String.prototype.indexOf () Method

if(window.location.href.indexOf("Desktop") > -1) {
       alert("Alert: Desktop!");
}

and for that you don’t need DOM Ready.

+9
source
<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
    if(window.location.href.indexOf("Desktop") > -1) {
       alert("Alert: Desktop!");
    }
});
</script>
</head>
<body>
    <h1>Test001</h1>
</body>
</html>

Please try this, it will give you permission.

+2
source

indexOf

console.log(window.location.href.indexOf("javascript"));

, - > -1 , -

0

regexp

url = window.location.href;
if( url.match(/desktop/gi) ) {
   alert("Alert: Desktop!");
}

, , "/desktop | home/gi"

0

jQuery, . , indexOf contains.

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    if(window.location.href.indexOf("Desktop") > -1) {
       alert("Alert: Desktop!");
    } else {
        alert("window.location.href: " + window.location.href);
    }
});
</script>
</head>
<body>
    <h1>Test001</h1>
</body>
</html>

. Javascript, f12 , , f5, . , . 'Uncaught ReferenceError: $is not defined' , .

0
var url = window.location.href;
            console.log(url);
            console.log(~url.indexOf("#product-consulation"));
            if (~url.indexOf("#product-consulation")) {
                console.log('YES');
                // $('html, body').animate({
                //     scrollTop: $('#header').offset().top - 80
                // }, 1000);
            } else {
                console.log('NOPE');
            }
0

Source: https://habr.com/ru/post/1623208/


All Articles