0

i have following urls, which i want to find a string and remove that string and anything before it.

String: me.do?page=

URL can be

http://demo.com/me.do?page=/facebook/link/home.php
http://demo.com/sub-folder/me.do?page=/facebook/link/home.php
http://**subdomain**.demo.com/sub-folder/demo/me.do?page=/facebook/link/home.php

final output should be

/facebook/link/home.php
/facebook/link/home.php
/facebook/link/home.php
Basit
  • 16,316
  • 31
  • 93
  • 154

3 Answers3

2

Don't really need regex even for this case:

var url = "http://demo.com/me.do?page=/facebook/link/home.php";
var result = url.split("/me.do?page=")[1];
Russ
  • 1,786
  • 13
  • 17
  • 1
    note that if there is another `"/me.do?page="` for some reason it will fail. To split and get everything after it even if the thing to split appears more than once [this question will be useful](http://stackoverflow.com/questions/11151542/javascript-split-to-split-string-in-2-parts-irrespective-of-number-of-spit-chara) – ajax333221 Jun 23 '12 at 17:27
  • I should probably explain there's a few caveats to this code. One is that `/me.do?page=` has to exist in the string or split will return an array of 1 string and you will get an index out of bounds error from [1]. Second, like @ajax333221 said if there is more than 1 `/me.do?page=` it will (or should) only grab the result between the first and second instance. The other answers provided here are more robust in these manners, but this is a quick and dirty solution that's rather readable – Russ Jun 23 '12 at 17:41
1
 var ur="http://demo.com/sub-folder/me.do?page=/facebook/link/home.php";
  var answer=ur.substring(ur.indexOf("me.do?page=")+11, ur.length);
Ashwin Singh
  • 7,197
  • 4
  • 36
  • 55
  • 1
    1st if anyone is wondering where the `+11` came from its the length of `me.do?page=`. 2nd the second parameter for `substring()` can be omitted to grab the rest of the string which is what `ur.length` does. This is more robust than my answer as it will find the first instance of `me.do?page=` and return the rest, but we have a 'magic number' dependent on the length of the string your searching for... – Russ Jun 23 '12 at 17:44
0

If you really feel you need a regex answer for this question, and bear in mind that string manipulation is faster/cheaper, there's:

var urls = ["http://demo.com/me.do?page=/facebook/link/home.php",
                    "http://demo.com/sub-folder/me.do?page=/facebook/link/home.php",
                    "http://**subdomain**.demo.com/sub-folder/demo/me.do?page=/facebook/link/home.php"],
    newUrls = [];

for (var i = 0, len = urls.length; i < len; i++) {
    var url = urls[i];
    newUrls.push(url.replace(/.+\/me\.do\?page\=/, ''));
}

console.log(newUrls);​

JS Fiddle demo.

David Thomas
  • 249,100
  • 51
  • 377
  • 410