482

How could I do something like this:

<script type="text/javascript">
$(document).ready(function () {
    if(window.location.contains("franky")) // This doesn't work, any suggestions?
    {
         alert("your url contains the name franky");
    }
});
</script>
1
  • 4
    "window.location.contains is not a function"
    – gene b.
    Sep 3, 2019 at 14:34

21 Answers 21

845

You need add href property and check indexOf instead of contains

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    if (window.location.href.indexOf("franky") > -1) {
      alert("your url contains the name franky");
    }
  });
</script>

7
  • 3
    I have a long URL like this, preview.tbwabox.co.nz/_v005/index.html#buying-a-car and I want to check if the string has "buying-a-car but the script" isn't working?
    – Vennsoh
    Jul 9, 2015 at 2:16
  • 8
    @Vennsoh You're not able to find "buying-a-car" because you need to look in window.location.hash not window.location.href. Simply swap those values out in OP's function. Oct 11, 2016 at 16:52
  • 2
    @J.W. Why` >-1` can't we use` >0`?
    – Elshan
    Jul 19, 2017 at 10:58
  • 5
    @Elshan Because, strictly speaking, .href.indexOf("franky") can return a value of 0 if .href begins with "franky". Of course, in this case, it never does as .href always begins with the protocol, typically "http:" or "file:". Despite this, you should ALWAYS use >-1, >=0 or, my preference, !==-1 when comparing with the result of indexOf().
    – robinCTS
    Aug 1, 2017 at 4:31
  • I have an array of value and want to see if the Url has any of the value and give me the index of the array that matches the condition. How do I do that? Thanks.
    – Si8
    Oct 11, 2018 at 19:24
130
if (window.location.href.indexOf("franky") != -1)

would do it. Alternatively, you could use a regexp:

if (/franky/.test(window.location.href))
3
  • 5
    A pros/cons between the two options would be a nice addition to this answer.
    – Chris
    Jan 7, 2019 at 19:21
  • 1
    But if I used an regex expression nobody would be able to read it ;) Jul 12, 2019 at 5:41
  • const url = new URL(window.location.href); const path = url.pathname; if (/^\/test($|\/|-)/.test(path)) { //do } This is the way Apr 28, 2023 at 14:39
37

You would use indexOf like this:

if(window.location.href.indexOf("franky") != -1){....}

Also notice the addition of href for the string otherwise you would do:

if(window.location.toString().indexOf("franky") != -1){....}
33

window.location isn't a String, but it has a toString() method. So you can do it like this:

(''+window.location).includes("franky")

or

window.location.toString().includes("franky")

From the old Mozilla docs:

Location objects have a toString method returning the current URL. You can also assign a string to window.location. This means that you can work with window.location as if it were a string in most cases. Sometimes, for example when you need to call a String method on it, you have to explicitly call toString.

2
  • 4
    In Firefox 48, String.prototype.contains() has been removed. Use String.prototype.includes() only. See Here
    – CaseyC
    Apr 14, 2017 at 21:39
  • @CaseyC Changed. Thanks!
    – Alin P.
    Apr 19, 2017 at 7:39
25

like so:

    <script type="text/javascript">
        $(document).ready(function () {
            if(window.location.href.indexOf("cart") > -1) 
            {
                 alert("your url contains the name franky");
            }
        });
    </script>
4
  • What's the difference between calling window.location.indexOf and window.location.href.indexOf? Feb 11, 2014 at 12:33
  • @starsplusplus There isn't any difference. window.location.href is an alias of window.location developer.mozilla.org/en-US/docs/Web/API/Window.location Feb 12, 2014 at 16:03
  • The above one works fine for me but for two variable how to check its contains the both the values Jul 11, 2016 at 12:16
  • 1
    @VinothNarayan You can simply add another condition to the if statement. To make sure it has both, you can use the AND operator, which is && in Javascript: if( window.location.href.indexOf("cart") > -1 && window.location.href.indexOf("box") > -1 ) To check if it has one or the other value, use the OR operator, which is two pipe characters || if( window.location.href.indexOf("cart") > -1 || window.location.href.indexOf("box") > -1 ) Oct 11, 2016 at 16:55
12

The regex way:

var matches = !!location.href.match(/franky/); //a boolean value now

Or in a simple statement you could use:

if (location.href.match(/franky/)) {

I use this to test whether the website is running locally or on a server:

location.href.match(/(192.168|localhost).*:1337/)

This checks whether the href contains either 192.168 or localhost AND is followed by :1337.

As you can see, using regex has its advantages over the other solutions when the condition gets a bit trickier.

3
  • Nice. I used if (window.parent.location.href.match(/\?/)) { window.parent.location = window.parent.location.pathname; } and it works very well...
    – Tarik
    Oct 8, 2015 at 16:12
  • Alternatively, it feels a bit more concise to me to use if(/franky/.test(location.href)) { /* regex matched */ } if I'm not doing anything with the matches. Jun 11, 2016 at 18:03
  • Yeah, test is definitely cleaner than match in this case. May 14, 2018 at 20:52
7

document.URL should get you the URL and

if(document.URL.indexOf("searchtext") != -1) {
    //found
} else {
    //nope
} 
6

Try this, it's shorter and works exactly as window.location.href:

if (document.URL.indexOf("franky") > -1) { ... }

also if you want to check the previous URL:

if (document.referrer.indexOf("franky") > -1) { ... }
1
  • @sixstarpro I didn't do the downvote, but, oh I don't know, maybe obviously because you gave the same answer as this one posted 18 months previously! Also, the extra info about document.referrer is completely irrelevant to the question.
    – robinCTS
    Aug 1, 2017 at 6:32
5

Easier it gets

<script type="text/javascript">
$(document).ready(function () {
    var url = window.location.href;
    if(url.includes('franky'))    //includes() method determines whether a string contains specified string.
    {
         alert("url contains franky");
    }
});
</script>
5

It will be a good practice if you convert your string to lower or uppercase as indexof() method is case sensitive.

This will be if your search isn't case sensitive you can simply use indexOf() method without converting the orignal string to lowercase or uppercase:

var string= location.href;
var convertedString= string.toLowerCase();

if(convertedString.indexOf('franky') != -1)
{
    alert("url has franky");
}
else
{
    alert("url has no franky");
}
5

I like this approach, instead.

top.location.pathname.includes('franky')

It works in many cases.

3

Try this:

<script type="text/javascript">             
    $(document).ready
    (
        function () 
        { 
            var regExp = /franky/g;
            var testString = "something.com/frankyssssddsdfjsdflk?franky";//Inyour case it would be window.location;
            if(regExp.test(testString)) // This doesn't work, any suggestions.                 
            {                      
                alert("your url contains the name franky");                 
            }             
        }
    );         
</script> 
3

Try indexOf

if (foo.indexOf("franky") >= 0)
{
  ...
}

You can also try search (for regular expressions)

if (foo.search("franky") >= 0)
{
  ...
}
3

a window location is an object that contains multiple methods and props some of them is strings related to URL so you can search for the targeted string safely:

const href = location.href;
// "https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string"

// another option 
const pathname = location.pathname;
// "/questions/4597050/how-to-check-if-the-url-contains-a-given-string"

// search for string safely
pathname.includes("questions"); // true
href.includes("questions"); // true

The Location Object

2

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

if (window.location.href.indexOf('franky') > -1) {
     alert("your url contains the name franky");
}
1
  • How to check if a url is default page and string iam checking is not visible . like for example sample.com/homepage.aspx is my page and iam looking for string 'homepage'. if((loc.toString().toUpperCase().indexOf('homepage') > -1)){} works fine but when Iam on sample.com(which still points to homepage.aspx) above code will not work.How to check for this scenario as well?please help!
    – Sweta
    Apr 15, 2016 at 5:12
2

I like to create a boolean and then use that in a logical if.

//kick unvalidated users to the login page
var onLoginPage = (window.location.href.indexOf("login") > -1);

if (!onLoginPage) {
  console.log('redirected to login page');
  window.location = "/login";
} else {
  console.log('already on the login page');
}
1

Put in your js file

                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');
                }
1
  • I didn't know ~, so I looked it up: "~ is a trick to turn indexOf()'s found return value into truthy (while making not-found as falsy). People otherwise use it for its side effect of truncating numbers..." - stackoverflow.com/a/12299678/3917091
    – Regular Jo
    Nov 3, 2017 at 16:06
1

Regular Expressions will be more optimal for a lot of people because of word boundaries \b or similar devices. Word boundaries occur when any of 0-9, a-z, A-Z, _ are on that side of the next match, or when an alphanumeric character connects to line or string end or beginning.

if (location.href.match(/(?:\b|_)franky(?:\b|_)))

If you use if(window.location.href.indexOf("sam"), you'll get matches for flotsam and same, among other words. tom would match tomato and tomorrow, without regex.

Making it case-sensitive is as simple as removing the i.

Further, adding other filters is as easy as

if (location.href.match(/(?:\b|_)(?:franky|bob|billy|john|steve)(?:\b|_)/i))

Let's talk about (?:\b|_). RegEx typically defines _ as a word character so it doesn't cause a word boundary. We use this (?:\b|_) to deal with this. To see if it either finds \b or _ on either side of the string.

Other languages may need to use something like

if (location.href.match(/([^\wxxx]|^)(?:franky|bob|billy|john|steve)([^\wxxx]|$)/i))
//where xxx is a character representation (range or literal) of your language's alphanumeric characters.

All of this is easier than saying

var x = location.href // just used to shorten the code
x.indexOf("-sam-") || x.indexOf("-sam.") || x.indexOf(" sam,") || x.indexOf("/sam")...
// and other comparisons to see if the url ends with it 
// more for other filters like frank and billy

Other languages' flavors of Regular Expressions support \p{L} but javascript does not, which would make the task of detecting foreign characters much easier. Something like [^\p{L}](filters|in|any|alphabet)[^\p{L}]

2
  • The only down side to regular expressions is they are "write only" ( ie. Impossible to read) ;) Nov 6, 2017 at 22:30
  • @RayLoveless Yeah, in languages without (?#comments) and freespacing # comments like javascript. However, this one isn't difficult to read. // When I use a complex regex in javascript, I keep a commented copy that I can edit lol.
    – Regular Jo
    Nov 7, 2017 at 2:42
1

This is my code ♥

function CheckUrl(url) {
var checkA = url.match(/(https|http):\/\/(.*?)\.(.*?)\.(.*?)(\/|'')/g);
var checkP = url.match(/(https|http):\/\/(.*?)\.(.*?)(\/|'')/g);
if (checkA != null || checkP != null) {
    return true;
}
else {
    console.log("Error", "The link is not valid");
}
return false;}
1

You can use javascript string method match

const url = window.location.href;
const find = 'questions';
const found = url.match(find);

console.log(url);

if(found !== null && found[0] === find){
  console.log('You are in the questions page');
} else {
  console.log('You are not in the questions page');
}

0

Suppose you have this script

<div>
  <p id="response"><p>
  <script>
    var query = document.location.href.substring(document.location.href.indexOf("?") + 1);
    var text_input = query.split("&")[0].split("=")[1];
    document.getElementById('response').innerHTML=text_input;
  </script> </div>

And the url form is www.localhost.com/web_form_response.html?text_input=stack&over=flow

The text written to <p id="response"> will be stack

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.