JavaScript function location.search regex help
I have a JavaScript function within an html file:
<!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>
The url I am on is:
http://somesuperlongstring.mydomain.com/somedirectory/index.html?commonHelpLocation=http://someothersuperlongstring.somedomain.com/help/index.html
Thus, location.search 开发者_StackOverflowreturns: http://someothersuperlongstring.somedomain.com/help/index.html
But the function returns the same string as well, however, the regex should return only ?commonHelpLocation=http://someothersuperlongstring.somedomain.com/help/index.html
Is there something wrong with my regex?
Is there something wrong with my regex?
Yes, ?
is a regular expression reserved character. You need to escape it for a literal ?
.
var queryString = location.search.replace(/^\?commonHelpLocation=/, '');
?
is a quantifier in regexps. You should escape it:
/^\?commonHelpLocation=/
To check if you are on a new page (and to stop reloading it) do the same regexp, only with the function of test
:
if (/^\?commonHelpLocation=/.test(location.search)) { /* reload */ }
精彩评论