Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a specific part of a URL using Javascript

I have a couple of URL's that I need to obtain a specific part of the last part of the URI

If I have the url www.test.co/index.php/government-printer-sales.html I only need to obtain government from the URL. All url's are in the same structure so if I have www.test.co/index.php/management-fees.html I need to obtain the word management

I tried the following

var str = document.URL.split('/');
 var type = str[5].split('-',1);

which gives me some result, but I'm sure there is a better way. If there's anyway I can obtain this from eiter mootools or just plain javascript

like image 447
Elitmiar Avatar asked Mar 18 '26 19:03

Elitmiar


2 Answers

You could use a regular expression to pull out the string after the last slash and before the first dash:

var regex = /\/([^/\-]+)[^/]*$/;
var matches = regex.exec('www.test.co/index.php/government-printer-sales.html');
var type = matches[1];  // government
like image 92
stevevls Avatar answered Mar 21 '26 08:03

stevevls


You can look here and then here and then check this code:

var myString = "www.test.co/index.php/government-printer-sales.html";
var myRegexp = /(www.test.co\/index.php\/)(\w+)-(.)*/g;
var match = myRegexp.exec(myString);
alert(match);
like image 23
madhead - StandWithUkraine Avatar answered Mar 21 '26 07:03

madhead - StandWithUkraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!