Kane
Kane

Reputation: 615

Current page URl check by JavaScript

I have tried to check the URL by this function. If we use single text then its working, but when we put the URL it's not working.

jQuery(document).ready
    (
        function () 
        { 
            //var regExp = /franky/g; //It's working 
            var regExp = /http://localhost/sitename/members/g; //its not working 
            var testString = "http://localhost/sitename/members/alan/course/";//In your case it would be window.location;
            var testString =  window.location;//Inyour case it would be window.location;
            if(regExp.test(testString)) // This doesn't work, any suggestions.                 
            {                      
                alert("your url match");                 
            }else{
                alert("Not match");   
            }             
        }
    ); 

Upvotes: 0

Views: 212

Answers (2)

Archana Agivale
Archana Agivale

Reputation: 405

You mention the wrong regex in your code,

 var regExp = /http://localhost/sitename/members/g;

Here you will get a syntax error. Instead of this, you can use regex like,

 var regExp = new RegExp("http://localhost/sitename/members");

OR

 var regExp = /http:\/\/localhost\/sitename\/members/g;

Upvotes: 2

John Doe
John Doe

Reputation: 1424

According to your question, what i understand is that your only goal is to check the url if it contain specific string or not. For that purpose you dont need a Regex. You can use JS include function to achieve your desired result.

jQuery(document).ready
(
    function () 
    { 
        var check_string = "localhost/sitename/members";
        var test_string = "http://localhost/sitename/members/alan/course/";

        if (test_string.includes(check_string))
        {                      
            alert("your url match");                 
        }
        else
        {
            alert("Not match");   
        }             
    }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Upvotes: 0

Related Questions