Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to check if URL contains a word

Tags:

javascript

I want to check if the URL in a Browser contains the word "Desktop" (I startet the html file from the Desktop). Its url is: "file:///C:/Users/Joe/Desktop/TestAlert.html"

But there should appear an alert, but this doesnt works.

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!

like image 548
Joe SharePoint Avatar asked Jan 07 '16 07:01

Joe SharePoint


People also ask

How do you check if the URL contains a given string in Javascript?

HTMLInputElement. checkValidity() method is used to check if a string in <input> element's value attribute is URL . The checkvalidity() method returns true if the value is a proper URL and false if the input is not a proper URL.

Does URL contain?

The URL contains the name of the protocol needed to access a resource, as well as a resource name. The first part of a URL identifies what protocol to use as the primary access medium. The second part identifies the IP address or domain name -- and possibly subdomain -- where the resource is located.

What does URL indexOf do?

What does URL indexOf do? The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.

How do you check if a URL has parameters or not?

To check if a url has query parameters, call the indexOf() method on the url, passing it a question mark, and check if the result is not equal to -1 , e.g. url. indexOf('? ') !== -1 .


1 Answers

The method is String.prototype.indexOf()

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

and you don't need DOM Ready for this.

like image 125
void Avatar answered Oct 19 '22 13:10

void