2011-07-12 14 views
0

私はhtmlファイル内のJavaScript機能を持っているJavaScriptの機能location.search正規表現のヘルプ

<!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> 

私は日午前URLは次のとおりです。したがって 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

私の正規表現に何か問題はありますか?

答えて

5

は、次のとおりです。

/^\?commonHelpLocation=/ 

だけtestの機能で、新しいページ上にあるかどうかを確認するには(そしてそれがリロードを停止する)同じ正規表現を行います私の正規表現に何か問題がありますか?

はい、?は、正規表現の予約文字です。あなたはリテラル?のためにそれをエスケープする必要があります。

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

?は、正規表現の量子です。あなたはそれをエスケープする必要があります

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

ええ....かなり愚かな間違い。修正しました、ありがとう! – TookTheRook

+0

+1、クエスチョンの第2部分に対処し、23秒も速くなる。 –

+0

はい - document.location.replace()は、ブラウザ内で他の場所を移動するためにも使用されます。これにより、正規表現置換の代わりにページの再読み込みが行われます。これを避けるには、document.locationプロパティを新しい変数に代入し、空の文字列を連結して参照を使わずに強制的に空の文字列にする - replace()をregexとして使用し、続く文字列をdocument.location.replace ()。 HTH。 – Ross

関連する問題