Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sborkman opened this issue May 10, 2017 · 0 comments
Open

Comments

@sborkman
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant