当前页面 URl 检查 JavaScript

Current page URl check by JavaScript

我试过用这个函数检查URL。如果我们使用单个文本,那么它可以工作,但是当我们放置 URL 时,它就不起作用了。

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");   
            }             
        }
    ); 

根据您的问题,我的理解是您的唯一目标是检查 url 是否包含特定字符串。为此,您不需要正则表达式。您可以使用 JS include 函数来实现您想要的结果。

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>

您在代码中提到了错误的正则表达式,

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

这里会出现语法错误。 取而代之的是,您可以使用正则表达式,例如

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

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