sammy
sammy copied to clipboard
Redirect function needs to escape special characters in regular expression
I found a problem with this part of the code:
// Changes the location of the current window. If
to` 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.