Jump to content

The Exec Method


iwato
 Share

Recommended Posts

The following code snippet fails, and I cannot understand why. The purpose of the code is to match the filename described by the RegExp called fileName against the URL defined by docURL. If a match is found it is supposed to alert the value of the matched filename.

<script type="text/javascript">function matchFilename() {	var docURL = location.href;	var fileName = new RegExp("js_filenameCapture.html");	var matchedName = fileName.exec(docURL);	if (matchedName == fileName) {		alert(matchedName);	}}matchFilename();</script>

Can you discover what is wrong?

Link to comment
Share on other sites

1. In a regular expression, the dot is a special character. If you're looking for a dot, you need to escape it.2. If you're searching for a specific string inside another string, it's faster if you don't use the entire regular expression engine. Regex is suited for pattern matching, not looking for a specific string. The string.indexOf method will look for a specific substring.3. You're comparing the return value of the regexp.exec method, which is an array, with a regexp object. An array is not going to be equivalent to a regexp object.

Link to comment
Share on other sites

1. In a regular expression, the dot is a special character. If you're looking for a dot, you need to escape it.
This is easily understood and correct. Thanks.
2. If you're searching for a specific string inside another string, it's faster if you don't use the entire regular expression engine. Regex is suited for pattern matching, not looking for a specific string. The string.indexOf method will look for a specific substring.
This is also easily understood, but will take additional code to correct. I will make an effort. Thanks, again.
3. You're comparing the return value of the regexp.exec method, which is an array, with a regexp object. An array is not going to be equivalent to a regexp object.
Even before I wrote, I saw this as a potential problem and tried to convert my recovered match with the String() method. As there were other errors, however, it made no difference. Thank you for confirming still another probable source of error. You have been a great help! What would W3Schools be worth, if it were not for people like you? A very special person. Many thanks!Roddy :)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...