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?

2
  • 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-]+).*$`). Commented Jun 28, 2018 at 12:53
  • 1
    Anyway, it has been explained a lot of times, closing with stackoverflow.com/questions/31969913/… as dupe reason. Commented Jun 28, 2018 at 12:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.