How to find javascript string of regular expressions from url?

Good evening, how can I find in javascript with a regular string of expression from url, for example, I have url: http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/ , and I only need a line between the last braid the dash (//) http://something.cz/something/string/ in this example that I need is a mikronebulizer. Thank you so much for your help.

0
source share
6 answers

You can use regex for a group.

Use this:

/([\w\-]+)\/$/.exec("http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/")[1]; 

Here jsfiddle shows it in action

This part: ([\w\-]+)

  • Means at least 1 or more sets of alphanumeric characters, underscores and hyphens and use them as the first group of matches.

What follows is /

And then finally: $

  • This means the line terminates with

..exec () returns an array in which the first value corresponds to a complete match (IE: "mikronebulizer /"), and then to each group of matches thereafter.

  • So .exec()[1] returns your value: mikronebulizer
0
source

Just:

 url.match(/([^\/]*)\/$/); 

Must do it.

If you want to combine (optionally) without a trailing slash, use:

 url.match(/([^\/]*)\/?$/); 

See here: http://regex101.com/r/cL3qG3

0
source

If you have a provided url, you can do it like this:

 var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/'; var urlsplit = url.split('/'); var urlEnd = urlsplit[urlsplit.length- (urlsplit[urlsplit.length-1] == '' ? 2 : 1)]; 

This will match either after the last slash, if there is any content there, otherwise it will match the part between the last and the last slash.

0
source

Something else to consider - yes, a pure RegEx method might be simpler (damn and faster), but I wanted to include this simply to specify window.location.pathName .

 function getLast(){ // Strip trailing slash if present var path = window.location.pathname.replace(/\/$?/, ''); return path.split('/').pop(); } 
0
source

Alternatively you can use split :

 var pieces = "http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/".split("/"); var lastSegment = pieces[pieces.length - 2]; // lastSegment == mikronebulizer 
0
source
  var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/'; if (url.slice(-1)=="/") { url = url.substr(0,url.length-1); } var lastSegment = url.split('/').pop(); document.write(lastSegment+"<br>"); 
0
source

All Articles