IT story

URL의 마지막 세그먼트

hot-time 2020. 4. 30. 07:35
반응형

URL의 마지막 세그먼트


URL의 마지막 세그먼트는 어떻게 얻습니까? 클릭 한 앵커 태그의 전체 URL을 표시하는 다음 스크립트가 있습니다.

$(".tag_name_goes_here").live('click', function(event)
{
    event.preventDefault();  
    alert($(this).attr("href"));
});

URL이

http://mywebsite/folder/file

경고 상자에 URL의 "파일"부분 만 표시하려면 어떻게합니까?


lastIndexOf () 함수를 사용 /하여 URL 에서 문자 의 마지막 항목을 찾은 다음 substring () 함수를 사용하여 해당 위치에서 시작하는 하위 문자열을 반환 할 수도 있습니다.

console.log(this.href.substring(this.href.lastIndexOf('/') + 1));

그렇게하면 모든 URL 세그먼트가 포함 된 배열을 만들지 않아도됩니다 split().


var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop();  // handle potential trailing slash

console.log(lastSegment);


window.location.pathname.split("/").pop()

정규식을 사용하는 또 다른 솔루션입니다.

var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);

Javascript에는 문자열 객체와 관련된 함수 분할 기능이 있으므로 다음을 수행 할 수 있습니다.

var url = "http://mywebsite/folder/file";
var array = url.split('/');

var lastsegment = array[array.length-1];

경로가 단순하고 간단한 경로 요소로만 구성된 경우 다른 답변이 효과가있을 수 있습니다. 그러나 쿼리 매개 변수가 포함되어 있으면 중단됩니다.

보다 강력한 솔루션을 얻으려면 대신 URL 객체를 사용 하는 것이 좋습니다. 현재 URL을 해석 한 것입니다.

입력: const href = 'https://stackoverflow.com/boo?q=foo&s=bar'

const last = new URL(href).pathname.split('/').pop();
console.log(last);

산출: 'boo'

이것은 모든 일반적인 브라우저에서 작동합니다. 죽어가는 IE만이 지원하지 않으며 지원하지 않습니다. IE의 경우 폴리 필이 가능합니다 (만약 관심이 있다면 ).


또는 정규식을 사용할 수 있습니다.

alert(href.replace(/.*\//, ''));

var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);

너무 늦었지만 다른 사람들에게는 PURL jquery plugin 사용을 적극 권장합니다 . PURL의 동기는 URL '#' 으로 분류 할 수 있다는 것입니다 (예 : angular.js 링크).

    http://test.com/#/about/us/

또는

    http://test.com/#sky=blue&grass=green

And with PURL you can easy decide (segment/fsegment) which segment you want to get.

For "classic" last segment you could write:

    var url = $.url('http://test.com/dir/index.html?key=value');
    var lastSegment = url.segment().pop(); // index.html

Building on Frédéric's answer using only javascript:

var url = document.URL

window.alert(url.substr(url.lastIndexOf('/') + 1));

Also,

var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);

If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).

url.split('/').filter(function (s) { return !!s }).pop()

// Store original location in loc like: http://test.com/one/ (ending slash)
var loc = location.href; 
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);

targetValue = one

If your url looks like:

http://test.com/one/

or

http://test.com/one

or

http://test.com/one/index.htm

Then loc ends up looking like: http://test.com/one

Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.

var targetValue = loc.substr(loc.lastIndexOf('/') + 1);

window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));

Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.

If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:

window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);

var pathname = window.location.pathname; // Returns path only
var url      = window.location.href;     // Returns full URL

Copied from this answer


To get the last segment of your current window:

window.location.href.substr(window.location.href.lastIndexOf('/') +1)


Returns the last segment, regardless of trailing slashes:

var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();

console.log(val);


Updated raddevus answer :

var loc = window.location.href;
loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);

Prints last path of url as string :

test.com/path-name = path-name

test.com/path-name/ = path-name

you can first remove if there is / at the end and then get last part of url

let locationLastPart = window.location.pathname
if (locationLastPart.substring(locationLastPart.length-1) == "/") {
  locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
}
locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);

I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.

window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));

I am using regex and split:

var last_path = location.href.match(/./(.[\w])/)[1].split("#")[0].split("?")[0]

In the end it will ignore # ? & / ending urls, which happens a lot. Example:

https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm

https://cardsrealm.com/profile/cardsRealm#hello -> Returns cardsRealm

https://cardsrealm.com/profile/cardsRealm?hello -> Returns cardsRealm

https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm


I don't really know if regex is the right way to solve this issue as it can really affect efficiency of your code, but the below regex will help you fetch the last segment and it will still give you the last segment even if the URL is followed by an empty /. The regex that I came up with is:

[^\/]+[\/]?$

// https://x.com/boo/?q=foo&s=bar = boo
// https://x.com/boo?q=foo&s=bar = boo
// https://x.com/boo/ = boo
// https://x.com/boo = boo

const segment = new 
URL(window.location.href).pathname.split('/').filter(Boolean).pop();
console.log(segment);

Works for me.


I know it is old but if you want to get this from an URL you could simply use:

document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);

document.location.pathname gets the pathname from the current URL. lastIndexOf get the index of the last occurrence of the following Regex, in our case is /.. The dot means any character, thus, it will not count if the / is the last character on the URL. substring will cut the string between two indexes.

참고URL : https://stackoverflow.com/questions/4758103/last-segment-of-url

반응형