Ian
Ian

Reputation: 1910

JavaScript regex using a character twice

So I'm using regex to grab information from a string, the issue is I need to both start up and stop at a / in the string.

Here's an example

var regexp = /\/(.*?)=(.*?)\//g;
    var url_hash = "/s=lorem+ipsum/p=2/";
    var match;
    var result = {};
    while ((match = regexp.exec(url_hash)) != null) {
     result[match[1]] = match[2];
  }

I can grab result['s'] without issue, but grabbing result['p'] becomes problematic, because the ending / for result['s'] is the same as the starting / for result['p']. If I changed the string to /s=lorem+ipsum//p=2/ it works perfectly, but of course that's hideous. So how can I fix this so that it both ends and starts up at the /? I'm stuck, any help is appreciated.

Upvotes: 1

Views: 314

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173652

You can determine the look-ahead set for part after the = yourself instead of adding it to the regular expression. The look-ahead set is "everything but a forward slash".

var regexp = /\/(\w+)=([^/]+)/g;

Btw, I'm assuming that the part before the = is word-like (i.e. alphanumeric)

Upvotes: 1

anubhava
anubhava

Reputation: 785876

Use this regex:

/\/([^/=]+)=([^/]+)/

Code:

var regexp = /\/([^/=]+)=([^/]+)/g;
var url_hash = "/#!/s=lorem+ipsum/p=2/";
var match;
var result = {};
while ((match = regexp.exec(url_hash)) != null) {
   result[match[1]] = match[2];
   document.writeln(match[1] + ' = ' + match[2] + '<br>');
}

OUTPUT:

s = lorem+ipsum
p = 2

Online demo of the code

Upvotes: 1

Blender
Blender

Reputation: 298492

Why can't you just split it?

var result = {};
var url = "/#!/s=lorem+ipsum/p=2/".slice(4, -1).split('/');

for (i in url) {
  var value = url[i].split('=');
  result[value[0]] = value[1];
}

console.log(result);

Upvotes: 1

Related Questions