Skip to content Skip to sidebar Skip to footer

How To Find In Javascript With Regular Expression String From Url?

Good evening, How can I find in javascript with regular expression string from url address for example i have url: http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/ and I nee

Solution 1:

You could use a regex match with a group.

Use this:

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

Here's a jsfiddle showing it in action

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

  • Means at least 1 or more of the set of alphanumeric, underscore and hyphen and use it as the first match group.

Followed by a /

And then finally the: $

  • Which means the line should end with this

The .exec() returns an array where the first value is the full match (IE: "mikronebulizer/") and then each match group after that.

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

Solution 2:

Simply:

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

Should do it.

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

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

See it in action here: http://regex101.com/r/cL3qG3

Solution 3:

If you have the url provided, then you can do it this way:

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 everything after the last slash, if there's any content there, and otherwise, it will match the part between the second-last and the last slash.

Solution 4:

Something else to consider - yes a pure RegEx approach might be easier (heck, and faster), but I wanted to include this simply to point out window.location.pathName.

functiongetLast(){
    // Strip trailing slash if presentvar path = window.location.pathname.replace(/\/$?/, '');
    return path.split('/').pop();
}

Solution 5:

Alternatively you could get using split:

var pieces = "http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/".split("/");

var lastSegment = pieces[pieces.length - 2];

// lastSegment == mikronebulizer

Post a Comment for "How To Find In Javascript With Regular Expression String From Url?"