visionmedia / page.js

Micro client-side router inspired by the Express router
http://visionmedia.github.com/page.js
7.67k stars 687 forks source link

path is broken in Context constructor #526

Closed onury closed 5 years ago

onury commented 5 years ago

Problem

This line:

this.path = path.replace(pageBase, '') || '/'

changes the path incorrectly by replacing (removing) the pageBase - first occurrence. It should remove the most left only, if there is any.

For example,

var pageBase = "/";
var path = "my/route/";
path.replace(pageBase, '');    // ——» produces "myroute/"

Solution

We need to escape regexp characters within pageBase:

function escapeRegExp(s) {
    return s.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1')
}

Then change the buggy line with:

// we'll ensure it only matches the start of the string.
var re = new RegExp('^' + escapeRegExp(pageBase));
this.path = path.replace(re, '') || '/';