quirkey / sammy

Sammy is a tiny javascript framework built on top of jQuery, It's RESTful Evented Javascript.
http://sammyjs.org
MIT License
2.99k stars 384 forks source link

Redirect function needs to escape special characters in regular expression #260

Open sborkman opened 7 years ago

sborkman commented 7 years ago

I found a problem with this part of the code:

// Changes the location of the current window. Ifto` begins with // '#' it only changes the document's hash. If passed more than 1 argument // redirect will join them together with forward slashes. // // ### Example // // redirect('#/other/route'); // // equivalent to // redirect('#', 'other', 'route'); // redirect: function() { var to, args = _makeArray(arguments), current_location = this.app.getLocation(), l = args.length; if (l > 1) { var i = 0, paths = [], pairs = [], params = {}, has_params = false; for (; i < l; i++) { if (typeof args[i] == 'string') { paths.push(args[i]); } else { $.extend(params, args[i]); has_params = true; } } to = paths.join('/'); if (has_params) { for (var k in params) { pairs.push(this.app._encodeFormPair(k, params[k])); } to += '?' + pairs.join('&'); } } else { to = args[0]; } this.trigger('redirect', {to: to}); this.app.last_location = [this.verb, this.path]; this.app.setLocation(to); if (new RegExp(to).test(current_location)) { this.app.trigger('location-changed'); }

},`

At the bottom, it uses a regular expression to see if the location changed. However, In my "to" variable, I had unmatched parentheses (it was a value in one of the parameters being sent in the URL). This caused an error in the constructor call to make a new RegExp object. I realized that the "to" variable was getting interpreted as a regular expression, and characters with special meaning in regular expressions were not getting escaped. I tried replacing the last part with this:

// http://stackoverflow.com/questions/2593637/how-to-escape-regular-expression-in-javascript if (new RegExp((to + '').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")).test(current_location)) { this.app.trigger('location-changed'); }

and it worked. As you can see, I left a link to the page that gave me the code to escape a string for a regular expression. I have to admit that I'm new to Sammy, so you might want to make sure this change does not conflict with how this function is intended to work before officially incorporating this new code.