最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

mootools - Getting a specific part of a URL using Javascript - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Oct 6, 2011 at 7:41 ElitmiarElitmiar 37k77 gold badges182 silver badges233 bronze badges 2
  • Is that the real URL? If there are only 2 slashes, then why do you access index 5 of the splitted string? – pimvdb Commented Oct 6, 2011 at 7:56
  • @pimvdb - just example, there can be more that two dashes – Elitmiar Commented Oct 6, 2011 at 9:45
Add a ment  | 

4 Answers 4

Reset to default 3

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

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);

Splice is a great function passing in a negative number as the first argument will create a new array with elements counting from the end of the array.

document.URL
> "http://stackoverflow./questions/7671441/getting-a-specific-part-of-a-url-using-javascript"

document.URL.split('/').splice(-1)[0].split('-')[0]
> "getting"

This is similar to python's list splicing lst[:-1]

Try this:

var type = window.location.pathname.match(/index.php\/([^-]+)(?:-)/)[1];

It searches for any characters following index.php/ excluding a hyphen, but followed by a single hyphen and fetches the value in between.

发布评论

评论列表(0)

  1. 暂无评论