我有一個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>
我的網址是: 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
我的正則表達式有什麼問題嗎?
是啊....非常愚蠢的錯誤。修好了,謝謝! – TookTheRook
+1,用於解決問題的第二部分,並且快23秒。 –
是的 - document.location.replace()也用於瀏覽器導航到其他地方,這將導致頁面重新加載,而不是正則表達式替換。爲了避免這種情況 - 將document.location屬性分配給一個新變量並連接(+)一個空字符串以強制複製而不是引用 - 那麼可以使用replace()作爲正則表達式並將隨後的字符串發送到document.location.replace ()。 HTH。 – Ross