Roger
Roger

Reputation: 1459

JavaScript match function seems to halt script

Yesterday 'Hnatt' was kind enough to offer the regex portion of this script :

<html>
<body>
    <script type="text/javascript">
        alert("hhhhhh   yadad   example.com/check?x=asdfasdf bsss ffhhh".match(/example.com\/check\?x\=([^\s]*)/)[1]);
        alert('alert 2');
    </script>
</body>
</html>

Now I have a new question/problem/point_of_confusion. If I change 'example.com' to not match, the entire script stops. I would like to know a solution other then try/catch that permits the script to continue forward. (Although, I hacked a fix with try/catch, insertion of a try catch/breaks the larger script... I don't know why. This is why I want a solution that is not comprised of try/catch). I would also like to try to understand why this halsting happens when the 'match' function does not find a match.

<html>
<body>
    <script type="text/javascript">
        alert("hhhhhh   yadad   exampleTwo.com/check?x=asdfasdf bsss ffhhh".match(/example.com\/check\?x\=([^\s]*)/)[1]);
        alert('alert 2');
    </script>
</body>
</html>

This is a boiled down version. In the broader script I am using the the needle found in the haystack and assigning it to a variable.

Upvotes: 2

Views: 619

Answers (3)

HBP
HBP

Reputation: 16033

Jeremy explains why you are getting the error. You can ensure that the index operation is valid as follows :

alert(("hhhhhh   yadad   exampleTwo.com/check?x=asdfasdf bsss ffhhh".match(/example.com\/check\?x\=([^\s]*)/) || [])[1]);

This turns the match result to an empty array if the match fails.

Upvotes: 0

jfriend00
jfriend00

Reputation: 707466

If you want to not generate a script error and not use try/catch, then you need to assign the match return value to a variable and test it to see if it found a match and if it found enough matches before using it.

var matches = "hhhhhh   yadad   exampleTwo.com/check?x=asdfasdf bsss ffhhh".match(/example.com\/check\?x\=([^\s]*)/);
if (matches && matches.length > 1) {
    alert(matches[1]);
}

Upvotes: 1

When there's no match, the .match() method returns null. When you attempt to get index [1] of null, there's an error, halting the script. You should check for this, something like:

var match = "hhhhhh   yadad   exampleTwo.com/check?x=asdfasdf bsss ffhhh".match(/example.com\/check\?x\=([^\s]*)/);
if (match) {
    alert(match[1]);
}
alert('alert 2');

Upvotes: 7

Related Questions