JavaScript函数location.search正则表达式帮助

Too*_*ook 0 html javascript regex

我在html文件中有一个JavaScript函数:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 <html>
    <head>
        <script type="text/javascript">
            function redirect() {
                var queryString = location.search.replace(/^?commonHelpLocation=/, '');
                alert(queryString);
                window.location = queryString;
            }
        </script>
    </head>
    <body onload="redirect();"></body>
</html>
Run Code Online (Sandbox Code Playgroud)

我的网址是: http://somesuperlongstring.mydomain.com/somedirectory/index.html?commonHelpLocation=http://someothersuperlongstring.somedomain.com/help/index.html

因此,location.search返回: http://someothersuperlongstring.somedomain.com/help/index.html

但是该函数也返回相同的字符串,但是,正则表达式应该只返回 ?commonHelpLocation=http://someothersuperlongstring.somedomain.com/help/index.html

我的正则表达式有问题吗?

kat*_*ugh 5

?是regexp中的量词.你应该逃避它:

/^\?commonHelpLocation=/
Run Code Online (Sandbox Code Playgroud)

要检查您是否在新页面上(并停止重新加载),请执行相同的正则表达式,仅使用以下函数test:

if (/^\?commonHelpLocation=/.test(location.search)) { /* reload */ }
Run Code Online (Sandbox Code Playgroud)


Jas*_*ary 5

我的正则表达式有问题吗?

是的,?是正则表达式保留字符.你需要逃避它的文字?.

var queryString = location.search.replace(/^\?commonHelpLocation=/, '');
Run Code Online (Sandbox Code Playgroud)