Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Try/Catch

I've got a function that runs a user generated Regex. However, if the user enters a regex that won't run then it stops and falls over. I've tried wrapping the line in a Try/Catch block but alas nothing happens.

If it helps, I'm running jQuery but the code below does not have it as I'm guessing that it's a little more fundamental than that.

Edit: Yes, I know that I am not escaping the "[", that's intentional and the point of the question. I'm accepting user input and I want to find a way to catch this sort of problem without the application falling flat on it's face.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <title>Regex</title>

    <script type="text/javascript" charset="utf-8">
        var grep = new RegExp('gr[');

        try
        {
            var results = grep.exec('bob went to town');
        }
        catch (e)
        {
            //Do nothing?
        }

        alert('If you can see this then the script kept going');
    </script>
</head>
<body>

</body>
</html>
like image 380
Teifion Avatar asked Sep 23 '08 12:09

Teifion


1 Answers

Try this the new RegExp is throwing the exception

Regex

    <script type="text/javascript" charset="utf-8">
            var grep;

            try {
                    grep = new RegExp("gr[");
            }
            catch(e) {
                    alert(e);

            }
            try
            {
                    var results = grep.exec('bob went to town');
            }
            catch (e)
            {
                    //Do nothing?
            }

            alert('If you can see this then the script kept going');
    </script>

like image 126
Paul Whelan Avatar answered Sep 19 '22 23:09

Paul Whelan