1

I've changed my query parameters format from &Key=Value to /Key/Value.

Now I'm trying to parse them in the url using regex. Not sure what I'm doing wrong but this is my code

Example url path: http://localhost/MyApp/#!/Page1/SubPage1/SubPage2/Key/value-example

let re = new RegExp(`^.*/(Key)/([a-zA-Z0-9]+).*$`);
while (match = re.exec(url)) {
    params[match[1]] = match[2];
}

It ends in a infinite loop

What am I doing wrong?

Gerald Hughes
  • 5,771
  • 20
  • 73
  • 131
  • 1
    It ends in an infinite loop because you did not compile the regex with `g` modifier. The regex index is not advanced and `while` always starts from the string start. Also, add `-` if there can be `-` in the value: `let re = new RegExp(\`^.*/(Key)/([a-zA-Z0-9-]+).*$\`, "g");`. However, if you do not expect multiple matches, just replace `while` with `if`, then the regex can be used without `g`, `new RegExp(\`^.*/(Key)/([a-zA-Z0-9-]+).*$\`)`. – Wiktor Stribiżew Jun 28 '18 at 12:53
  • 1
    Anyway, it has been explained a lot of times, closing with https://stackoverflow.com/questions/31969913/why-does-this-regexp-exec-cause-an-infinite-loop as dupe reason. – Wiktor Stribiżew Jun 28 '18 at 12:57

1 Answers1

1

Instead of using regular expressions, I would suggest a more straight forward approach of using split().

var url = 'http://localhost/MyApp/#!/Page1/SubPage1/SubPage2/Key/value-example'
var keyName = 'Key'
var urlParts = url.split('/')
var keyIndex = urlParts.indexOf(keyName) // "Key" is at index #8
// Since the value appears right after the key, we can access it by increasing the index by 1
var value = urlParts[keyIndex + 1] // "value-example" is at index #9

Here is the result of the command url.split('/'):

[ 'http:',
  '',
  'localhost',
  'MyApp',
  '#!',
  'Page1',
  'SubPage1',
  'SubPage2',
  'Key',
  'value-example' ]

So what we are doing is locating the index of the desired key in the array and looking at the next value - index+1.

Lix
  • 47,311
  • 12
  • 103
  • 131