programing

JavaScript - URL 경로의 일부를 가져옵니다.

yoursource 2022. 11. 2. 23:41
반응형

JavaScript - URL 경로의 일부를 가져옵니다.

JavaScript를 사용하여 URL에서 경로만 추출하는 올바른 방법은 무엇입니까?

예:
URL이 있습니다.
http://www.somedomain.com/account/search?filter=a#top
이 정도만 받고 싶어요.
/account/검색

활용할 수 있는 것이 있다면 jQuery를 사용하고 있습니다.

현재 창에 제공하는 기본 제공 개체의 속성이 있습니다.

// If URL is http://www.somedomain.com/account/search?filter=a#top

window.location.pathname // /account/search

// For reference:

window.location.host     // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash     // #top
window.location.href     // http://www.somedomain.com/account/search?filter=a#top
window.location.port     // (empty string)
window.location.protocol // http:
window.location.search   // ?filter=a  


업데이트, 모든 URL에 동일한 속성을 사용합니다.

이 스키마는 URLUtils라는 인터페이스로 표준화 되어 있습니다.그게 뭘까요?기존 둘 다window.locationobject 요소와 anchor 요소는 인터페이스를 구현합니다.

따라서 URL에 대해 위의 동일속성사용할 수 있습니다. URL을 사용하여 앵커를 만들고 속성에 액세스하기만 하면 됩니다.

var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";

el.host        // www.somedomain.com (includes port if there is one[1])
el.hostname    // www.somedomain.com
el.hash        // #top
el.href        // http://www.somedomain.com/account/search?filter=a#top
el.pathname    // /account/search
el.port        // (port if there is one[1])
el.protocol    // http:
el.search      // ?filter=a

[1]: 포트가 포함된 속성에 대한 브라우저 지원이 일관되지 않습니다.참조: http://jessepollak.me/chrome-was-wrong-ie-was-right

이 기능은 ChromeFirefox의 최신 버전에서 작동합니다.테스트할 Internet Explorer 버전이 없으므로 JSFiddle의 예를 사용하여 직접 테스트해 보십시오.

JSFiddle 예시

앵커 요소 없이 URL 자체를 지원하는 새로운 객체도 있습니다.현재 안정적인 브라우저는 지원하지 않는 것으로 보이지만 파이어폭스 26에서 제공되는 것으로 알려져 있습니다.지원을 받을있을같으면 여기에서 시도해 보십시오.

window.location.href.split('/');

모든 URL 부분을 포함하는 어레이가 제공되며 일반 어레이처럼 액세스할 수 있습니다.

또는 @Dylan이 제안하는 보다 우아한 솔루션에는 다음과 같은 경로 부분만 포함되어 있습니다.

window.location.pathname.split('/');

이것이 현재 URL인 경우 window.location.pathname을 사용하지 않으면 다음 정규식을 사용합니다.

var reg = /.+?:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];

URL이라는 유용한 웹 API 방법이 있습니다.

const url = new URL('https://www.somedomain.com/account/search?filter=a#top');
console.log(url.pathname.split('/').slice(1)); // drop the leading slash
const params = new URLSearchParams(url.search)
console.log("filter:",params.get("filter"))

추상 URL 문자열이 있는 경우(현재 URL 문자열이 아님)window.location)는, 다음의 트릭을 사용할 수 있습니다.

let yourUrlString = "http://example.com:3000/pathname/?search=test#hash";

let parser = document.createElement('a');
parser.href = yourUrlString;

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

jlong 덕분에

변수에 저장한 URL의 일부를 가져오고 싶다면 URL-Parse를 추천합니다.

const Url = require('url-parse');
const url = new Url('https://github.com/foo/bar');

설명서에 따르면 다음 부분을 추출합니다.

반환된 URL 인스턴스에는 다음 속성이 포함됩니다.

프로토콜:URL의 프로토콜 구성표(예: http:).slashes: 프로토콜 뒤에 슬래시(/)가 두 개 계속되는지 여부를 나타내는 부울입니다. auth:인증 정보 부분(예: username: password).사용자 이름:기본 인증 사용자 이름password : 기본 인증 비밀번호.host: 포트 번호가 있는 호스트 이름.호스트명:포트 번호가 없는 호스트 이름.port: 옵션의 포트 번호.pathname : URL 경로.query: 구문 해석이 false로 설정되어 있지 않는 한 쿼리 문자열을 포함하는 구문 분석 개체.hash: 파운드 기호(#)를 포함한 URL의 "fragment" 부분.href: 완전한 URL. 오리진:URL의 발신기지.

언급URL : https://stackoverflow.com/questions/6944744/javascript-get-portion-of-url-path

반응형