Reputation: 3130
I have the following regex to get the first part after a url:
^http[s]?:\/\/.*?\/([a-zA-Z-_.%]+).*$
It matches test in the below urls:
foo.com
http://foo.com
http://foo.com/test
http://foo.com/test/
http://foo.com/test?bar
What I'm now trying to do is recreate the same url, but replace test with a different value. Either by taking the parts before and after the match or reversing the result.
I'm sure there's a regexy way of doing this, but I'm unable to find out how to do so.
Upvotes: 0
Views: 229
Reputation: 784898
You can use a capturing group for part before /test
and use it as back-reference in replacement:
var re = /^(https?:\/\/[^\/]+\/)[^?\/]+/gmi;
var subst = '$1foobar';
var result = str.replace(re, subst);
[^?\/]+
will match text before next /
or ?
after domain name in URL. As your original regex it also assumes that URLs start with http://
or https://
.
Upvotes: 2