【问题标题】:JavaScript function location.search regex helpJavaScript 函数 location.search 正则表达式帮助
【发布时间】:2011-07-12 21:03:07
【问题描述】:

我在一个 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>

我所在的网址是: 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

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

【问题讨论】:

    标签: javascript html regex


    【解决方案1】:

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

    是的,? 是正则表达式保留字符。您需要将其转义为文字 ?。

    var queryString = location.search.replace(/^\?commonHelpLocation=/, '');
    

    【讨论】:

      【解决方案2】:

      ? 是正则表达式中的量词。你应该逃避它:

      /^\?commonHelpLocation=/
      

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

      if (/^\?commonHelpLocation=/.test(location.search)) { /* reload */ }
      

      【讨论】:

      • +1,用于解决问题的第二部分并快 23 秒。
      • 是的 - document.location.replace() 也用于浏览器中导航到其他地方,这将导致页面重新加载而不是正则表达式替换。为避免这种情况 - 将 document.location 属性分配给一个新变量并连接 (+) 一个空字符串以强制复制而不是引用 - 然后您可以使用 replace() 作为正则表达式并将随后的字符串发送到 document.location.replace ()。 HTH。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-30
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      相关资源
      最近更新 更多