programing

URL에서 fragment ID(해시 번호 이후의 값)를 취득하려면 어떻게 해야 합니까?

randomtip 2022. 9. 14. 22:08
반응형

URL에서 fragment ID(해시 번호 이후의 값)를 취득하려면 어떻게 해야 합니까?

예:

www.site.com/index.php#hello

jQuery를 사용하여 값을 입력합니다.hello변수:

var type = …

jQuery 불필요

var type = window.location.hash.substr(1);

이 작업은 다음 코드를 사용하여 수행할 수 있습니다.

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);

데모 참조

var url ='www.site.com/index.php#hello';
var type = url.split('#');
var hash = '';
if(type.length > 1)
  hash = type[1];
alert(hash);

jsfiddle 작업 데모

다음 JavaScript를 사용하여 URL에서 해시(#) 뒤의 값을 가져옵니다. 이 값을 위해 jQuery를 사용할 필요는 없습니다.

var hash = location.hash.substr(1);

이 코드와 튜토리얼을 여기서 입수했습니다.JavaScript를 사용하여 URL에서 해시값을 취득하는 방법

아주 쉬워요.아래 코드를 사용해 보십시오.

$(document).ready(function(){
  var hashValue = location.hash.replace(/^#/, '');  
  //do something with the value here  
});

실행 시 URL을 확인했는데, 아래가 정답입니다.

let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);

이것이 도움이 되기를 바란다

A를 기준으로 합니다.K의 코드, 여기 도우미 함수가 있습니다.JS Fidle Here(http://jsfiddle.net/M5vsL/1/)...)

// Helper Method Defined Here.
(function (helper, $) {
    // This is now a utility function to "Get the Document Hash"
    helper.getDocumentHash = function (urlString) {
        var hashValue = "";

        if (urlString.indexOf('#') != -1) {
            hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
        }
        return hashValue;
    };
})(this.helper = this.helper || {}, jQuery);

현재 문서 위치의 조각 가져오기

var hash = window.location.hash;

문자열에서 조각 가져오기

// absolute
var url = new URL('https://example.com/path/index.html#hash');

console.log(url.hash);

// relative (second param is required, use any valid URL base)
var url2 = new URL('/path/index.html#hash2', 'http://example');

console.log(url2.hash);

언급URL : https://stackoverflow.com/questions/11662693/how-do-i-get-the-fragment-identifier-value-after-hash-from-a-url

반응형