Reputation:
I've run into a strange problem that I can't seem to get around... Basically, I've got this Regex that's returning the stuff that I don't have in a capture group, and it's not returning the actual captured group. Here is the Regex:
"localhost/a/b/c".match(/\/a\/b\/(.*?)/g);
To my knowledge, this is supposed to return ["c"]
... But it returns:
["/a/b/"]
What am I doing wrong? I thought captured groups were supposed to be returned, not ignored.
Upvotes: 4
Views: 229
Reputation: 19571
Try: "localhost/a/b/c".match(//a/b/(.+)/)[1]
In your original regex "localhost/a/b/c".match(/\/a\/b\/(.*?)/g);
.
means any character *
means previous character class matched 0 - infinite times ?
means to match as few of previously specified characters as possible while still matching the rest of the regex but since there is nothing after the group this group will effectively capture nothingg
modifier here at least not with this example.$('#myDiv').append( "localhost/a/b/c".match(/\/a\/b\/(.+)/)[1] );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"><div>
Upvotes: 6