0

i need to trim this string -> http://hokuspokus/ixdebude/ix and i exactly Need this part of the string /ixdebude/ix

I have 2 expressions to solve my Problem.

My first regex ->

/(.*)\/(.*)(\/)(.*)\/*/g returns Array[5] groups .

my second regex ->

/(\/............)$(.*?)$/g returns /ixdebude/ix

Can someone of you give me another regex, a better without thousand dots ?

  • 1
    Why not just use `split`? – j08691 Sep 21 '16 at 14:54
  • 2
    Additionally - that link / string is not a valid URL. If your regex needs to support valid URL's, you might want to address that. Also - what is special about the `ixdebude/ix` part? Is it the first part after the domain name? Or something else? – random_user_name Sep 21 '16 at 14:55
  • 2
    Do you know what the domain name is in advance? That will make it trivial and not require any regex. – VLAZ Sep 21 '16 at 14:55
  • Also - you should see this question / answer. Your first regex may do what you want IF you understand how to access the information: http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression?rq=1 – random_user_name Sep 21 '16 at 14:56
  • @cale_b well, the first part could be valid. imagine `localhost/mypage.html` - as long as DNS resolves it, it can be a link – VLAZ Sep 21 '16 at 14:57
  • 1
    This is a very confusing question. Literally you can use `"http://hokuspokus/ixdebude/ix".match(/\/ixdebude\/ix/)`. It would be helpful to know more than one case you need to match against. Is it always two segments and always at the end? Then you can use `/\/[^/]+\/[^/]+$/`. Is it always immediately after a url? Is there more than one match in a single string possible? – Joseph Marikle Sep 21 '16 at 14:58

2 Answers2

4

You could use a regex like this:

//.*?(/.*)

Working demo

For javascript, you could use:

var re = /\/\/.*?(\/.*)/; 
var str = 'http://hokuspokus/ixdebude/ix';
var m;

if ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}
Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
3

You could try this

var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

https://gist.github.com/jlong/2428561

Millard
  • 1,157
  • 1
  • 9
  • 19
  • 1
    Yeah, not mine sadly. Credit goes to - https://gist.github.com/jlong. Just put the code here incase it ever gets deleted. – Millard Sep 21 '16 at 15:07