当前页面 JavaScript 的 URl 检查

Current page URl check by JavaScript

提问人:Kane 提问时间:2/10/2021 更新时间:2/10/2021 访问量:135

问:

我试图通过这个功能检查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");   
            }             
        }
    ); 
JavaScript jQuery URL 匹配

评论

0赞 Mohammad 2/10/2021
你应该在喜欢中转义斜杠regExp/http:\/\/localhost\/sitename\/members/g

答:

0赞 John Doe 2/10/2021 #1

根据您的问题,我的理解是,您唯一的目标是检查网址是否包含特定字符串。为此,您不需要正则表达式。您可以使用 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>

2赞 Archana Agivale 2/10/2021 #2

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

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

在这里,您将收到语法错误。 取而代之的是,您可以使用正则表达式,例如,

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

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