]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
fix: escape regex chars
authorEduardo San Martin Morote <posva13@gmail.com>
Wed, 12 Feb 2020 10:55:14 +0000 (11:55 +0100)
committerEduardo San Martin Morote <posva13@gmail.com>
Wed, 12 Feb 2020 10:55:14 +0000 (11:55 +0100)
__tests__/matcher/path-parser.spec.ts
src/matcher/path-parser-ranker.ts

index 82c625c81a0ff12a3a4279430fba7a1f3451f23c..1e314e3e63c9b62f672032344db9da384a27fce9 100644 (file)
@@ -374,6 +374,33 @@ describe('Path parser', () => {
       matchRegExp('^/$', [[]], { strict: true })
     })
 
+    it('regex special characters', () => {
+      matchRegExp('^/foo\\+\\.\\*\\?$', [
+        [{ type: TokenType.Static, value: 'foo+.*?' }],
+      ])
+      matchRegExp('^/foo\\$\\^$', [
+        [{ type: TokenType.Static, value: 'foo$^' }],
+      ])
+      matchRegExp('^/foo\\[ea\\]$', [
+        [{ type: TokenType.Static, value: 'foo[ea]' }],
+      ])
+      matchRegExp('^/foo\\(e|a\\)$', [
+        [{ type: TokenType.Static, value: 'foo(e|a)' }],
+      ])
+      matchRegExp('^/(\\d+)\\{2\\}$', [
+        [
+          {
+            type: TokenType.Param,
+            value: 'id',
+            regexp: '\\d+',
+            repeatable: false,
+            optional: false,
+          },
+          { type: TokenType.Static, value: '{2}' },
+        ],
+      ])
+    })
+
     it('strict /', () => {
       matchRegExp('^/$', [[{ type: TokenType.Static, value: '' }]], {
         strict: true,
index cd592cc4c6fa8a126e34af2ddbe2cc13065eaafb..847348d774a5cc8a521e0f6d58c7ba17ce29b56f 100644 (file)
@@ -87,6 +87,9 @@ const enum PathScore {
   BonusCaseSensitive = 0.025 * _multiplier, // when options strict: true is passed, as the regex omits \/?
 }
 
+// Special Regex characters that must be escaped in static tokens
+const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g
+
 /**
  * Creates a path parser from an array of Segments (a segment is an array of Tokens)
  *
@@ -126,7 +129,7 @@ export function tokensToParser(
       if (token.type === TokenType.Static) {
         // prepend the slash if we are starting a new segment
         if (!tokenIndex) pattern += '/'
-        pattern += token.value
+        pattern += token.value.replace(REGEX_CHARS_RE, '\\$&')
         subSegmentScore += PathScore.Static
       } else if (token.type === TokenType.Param) {
         const { value, repeatable, optional, regexp } = token