0

take this url

http://service.com/room/dothings?adsf=asdf&dafadsf=dfasdf
http://service.com/room/saythings?adsf=asdf&dafadsf=dfasdf

say if i want to capture dothings, saythings, I now the following regex

/room\/(.+)\?/.exec(url)

and in the result i get this.

["room/dothings?", "dothings"]

what should i write to obtain the string above with only one item in an array.

2
  • 1
    You can't. The first element in the result is always the full match. All other elements are the group matches (stuf). You could chain it though: /x/.exec(y)[1] or y.match(/x/)[1] Commented May 14, 2014 at 0:37
  • thanks. i was looking for someone to verify Commented May 14, 2014 at 4:58

2 Answers 2

1

I know this doesn't answer your question, but parsing a URL with regex is not easy, and in some cases not even safe. I would do the parsing without regex.

In browser:

var parser = document.createElement('a');
parser.href = 'http://example.com/room/dothings?adsf=asdf&dafadsf=dfasdf';

In node.js:

var url = require('url');
var parser = url.parse('http://example.com/room/dothings?adsf=asdf&dafadsf=dfasdf');

And then in both cases:

console.log(parser.pathname.split('/')[2]);
Sign up to request clarification or add additional context in comments.

Comments

1

That's actually easy. You were almost there.

With all the obligatory disclaimers about parsing html in regex...

<script>
var subject = 'http://service.com/room/dothings?adsf=asdf&dafadsf=dfasdf';
var regex = /room\/(.+)\?/g;
var group1Caps = [];
var match = regex.exec(subject);
while (match != null) {
    if( match[1] != null ) group1Caps.push(match[1]);
    match = regex.exec(subject);
}
if(group1Caps.length > 0) document.write(group1Caps[0],"<br>");
</script>

Output: dothings

If you add strings in subject you can for (key in group1Caps) and it will spit out all the matches.

Online demo

3 Comments

thanks, what I looking for was a way to use regex to extract the target directly.
@user2167582 So that's what you want, or am I misunderstanding your comment?
what you wrote returns a single match, but what i was looking for was a pattern that returns only the capture group and not the entire expression, so in many frameworks such as angular, there are filters that uses ng-pattern for matching regex, if i use capture groups, it would return my desired result on second paramemter which is not useful and i sometimes need to rewrite, so a regex or a way to use regex in javascript such that matching expression isn't captured by default is what I was looking for. but if not i can rewrite over default patterns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.