475

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>
Smi
  • 13,850
  • 9
  • 56
  • 64
RayLoveless
  • 19,880
  • 21
  • 76
  • 94

21 Answers21

838

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>
double-beep
  • 5,031
  • 17
  • 33
  • 41
J.W.
  • 17,991
  • 7
  • 43
  • 76
  • 3
    I have a long URL like this, http://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 09 '15 at 02: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. – Adrian Gonzales Oct 11 '16 at 16:52
  • 2
    @J.W. Why` >-1` can't we use` >0`? – Elshan Jul 19 '17 at 10:58
  • 5
    @Elshan Because, strictly speaking, `.href.indexOf("franky")` [can return a value of 0](https://www.w3schools.com/jsref/jsref_indexof.asp) 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()`](https://www.w3schools.com/jsref/jsref_indexof.asp). – robinCTS Aug 01 '17 at 04: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 '18 at 19:24
  • you can also use ~ (NOT operator) instead of checking > -1. NOT operator turns -1 to 0 (false), in case of indexOf which returns the position of match so NOT operator returns a negative value (which is true, all values other than 0 is true). 0 = false -1 = true 1 = true eg: if(~window.location.href.indexOf('franky')) { alert(' text goes here') } – CaptainZero Apr 18 '19 at 06:50
  • 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 mind full – GeniusGeek Apr 30 '20 at 21:11
128
if (window.location.href.indexOf("franky") != -1)

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

if (/franky/.test(window.location.href))
Darian Moody
  • 3,565
  • 1
  • 22
  • 33
NickFitz
  • 34,537
  • 8
  • 43
  • 40
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){....}
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
30

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.

robinCTS
  • 5,746
  • 14
  • 30
  • 37
Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
  • 3
    In Firefox 48, String.prototype.contains() has been removed. Use String.prototype.includes() only. [See Here](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes) – CaseyC Apr 14 '17 at 21:39
  • @CaseyC Changed. Thanks! – Alin Purcaru Apr 19 '17 at 07: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>
Adrian Gonzales
  • 1,010
  • 6
  • 8
  • What's the difference between calling window.location.indexOf and window.location.href.indexOf? – starsplusplus Feb 11 '14 at 12:33
  • @starsplusplus There isn't any difference. `window.location.href` is an alias of `window.location` https://developer.mozilla.org/en-US/docs/Web/API/Window.location – Adrian Gonzales Feb 12 '14 at 16:03
  • The above one works fine for me but for two variable how to check its contains the both the values – Vinoth Narayan Jul 11 '16 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 )` – Adrian Gonzales Oct 11 '16 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.

Stephan Bijzitter
  • 4,425
  • 5
  • 24
  • 44
  • Nice. I used if (window.parent.location.href.match(/\?/)) { window.parent.location = window.parent.location.pathname; } and it works very well... – Tarik Oct 08 '15 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. – cchamberlain Jun 11 '16 at 18:03
  • Yeah, `test` is definitely cleaner than `match` in this case. – Stephan Bijzitter May 14 '18 at 20:52
7

document.URL should get you the URL and

if(document.URL.indexOf("searchtext") != -1) {
    //found
} else {
    //nope
} 
Xeon
  • 5,949
  • 5
  • 31
  • 52
ChillaraDonga
  • 73
  • 1
  • 3
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) { ... }
Praveen
  • 55,303
  • 33
  • 133
  • 164
sixstarpro
  • 81
  • 1
  • 5
  • @sixstarpro I didn't do the downvote, but, oh I don't know, maybe obviously because you gave the same answer as [this one](https://stackoverflow.com/a/10923708/1961728) posted 18 months previously! Also, the extra info about `document.referrer` is completely irrelevant to the question. – robinCTS Aug 01 '17 at 06: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>
Vishnu Dev
  • 59
  • 1
  • 5
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");
}
Hammad Sajid
  • 312
  • 1
  • 3
  • 14
GeniusGeek
  • 315
  • 6
  • 14
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> 
Chandu
  • 81,493
  • 19
  • 133
  • 134
3

Try indexOf

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

You can also try search (for regular expressions)

if (foo.search("franky") >= 0)
{
  ...
}
Yoni Baciu
  • 2,667
  • 1
  • 22
  • 28
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");
}
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
  • 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 '16 at 05: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');
}
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
2

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

Muhammed Moussa
  • 4,589
  • 33
  • 27
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');
                }
alemac852
  • 99
  • 1
  • 11
  • 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..."** - https://stackoverflow.com/a/12299678/3917091 – Regular Jo Nov 03 '17 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}]

Regular Jo
  • 5,190
  • 3
  • 25
  • 47
  • The only down side to regular expressions is they are "write only" ( ie. Impossible to read) ;) – RayLoveless Nov 06 '17 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 07 '17 at 02: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');
}
Ovi
  • 179
  • 1
  • 4
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

Regular Jo
  • 5,190
  • 3
  • 25
  • 47
Dhiraj Himani
  • 1,062
  • 12
  • 9