itsource

JavaScript URL 디코드 기능

mycopycode 2023. 8. 30. 21:41
반응형

JavaScript URL 디코드 기능

최고의 자바스크립트 URL 디코딩 유틸리티는 무엇입니까?인코딩도 좋을 것 같고 jQuery로 잘 작동하는 것은 추가 보너스입니다.

PHPJS에서 가져온 완전한 함수는 다음과 같습니다.

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}

인코딩을 사용했습니다.URI 구성 요소()디코딩URI 구성 요소()도 마찬가지입니다.

사용

unescape(str);

저는 훌륭한 JS 프로그래머가 아닙니다. 모든 것을 시도했고, 이것은 훌륭했습니다!

decodeURIComponent(mystring);

다음 코드를 사용하여 전달된 매개 변수를 얻을 수 있습니다.

//parse URL to get values: var i = getUrlVars()["i"];
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

또는 이 한 줄로 매개변수를 가져옵니다.

location.search.split("your_parameter=")[1]
//How decodeURIComponent Works

function proURIDecoder(val)
{
  val=val.replace(/\+/g, '%20');
  var str=val.split("%");
  var cval=str[0];
  for (var i=1;i<str.length;i++)
  {
    cval+=String.fromCharCode(parseInt(str[i].substring(0,2),16))+str[i].substring(2);
  }

  return cval;
}

document.write(proURIDecoder(window.location.href));

만약 당신이 urlencode를 사용하여 PHP의 데이터를 인코딩하는 책임이 있다면, PHP의 rawurlencode는 JavaScript의 디코딩과 함께 작동합니다.+ 문자를 교체할 필요가 없는 URI 구성 요소.

제가 사용한 것은 다음과 같습니다.

JavaScript에서:

var url = "http://www.mynewsfeed.com/articles/index.php?id=17";
var encoded_url = encodeURIComponent(url);

var decoded_url = decodeURIComponent(encoded_url);

PHP에서:

$url = "http://www.mynewsfeed.com/articles/index.php?id=17";
$encoded_url = url_encode(url);

$decoded_url = url_decode($encoded_url);

http://www.mynewsfeed.x10.mx/articles/index.php?id=17 에서 온라인으로 사용해 볼 수도 있습니다.

var uri = "my test.asp?name=ståle&car=saab";
console.log(encodeURI(uri));

decodeURIComponent()괜찮아요, 하지만 당신은 절대 사용하고 싶지 않을 거예요.encodeURIComponent()직접적으로.이는 다음과 같은 예약된 문자를 이스케이프하지 못합니다.*,!,',(,그리고.)이에 대한 자세한 내용은 RFC3986에서 확인하십시오.Mozilla Developer Network 설명서는 유용한 설명과 해결 방법을 모두 제공합니다.설명...

RFC 3986(!, ', (, ) 및 *를 예약함)을 더욱 엄격하게 준수하려면 공식화된 URI 구분 사용이 없더라도 다음을 안전하게 사용할 수 있습니다.

솔루션...

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

확실하지 않은 경우, JSBin.com 에서 효과적인 데모를 확인하십시오.JSBin.com 에서 직접 사용하는 좋지 않은 작동 데모와 비교해 보십시오.

양호한 코드 결과:

thing%2athing%20thing%21

잘못된 코드 결과encodeURIComponent():

thing*thing%20thing!

언급URL : https://stackoverflow.com/questions/4292914/javascript-url-decode-function

반응형