JavaScript에서 URL을 인코딩하시겠습니까?
JavaScript를 사용하여 URL을 GET 문자열에 넣을 수 있도록 안전하게 인코딩하려면 어떻게 해야 합니까?
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
경우 부호화가 됩니다.myUrl
두번 줄줄 ?? ?? ?? ??
내장 함수 인코딩을 확인합니다.URIC 컴포넌트(str) 및 부호화URI(str).
같은 될 거예요.
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
다음의 3가지 옵션이 있습니다.
escape()
부호화되지 .「 」 。@*/+
encodeURI()
부호화되지 .「 」 。~!@#$&*()=:/,;?+'
encodeURIComponent()
부호화되지 .「 」 。~!*()'
단, 고객님의 경우 URL을 에 전달하려면GET
는 '하다, 하다, 하다, 하다'를 사용합니다.escape
★★★★★★★★★★★★★★★★★」encodeURIComponent
않다.encodeURI
.
스택 오버플로우 질문 모범 사례: 이스케이프 또는 인코딩을 참조하십시오.URI / 인코딩자세한 논의를 위한 URICoomponent.
그대로 있어.이 함수는 URL에서 의미적으로 중요한 많은 문자(예: "#", "?", "&")를 부호화하지 않으며 "+" 문자를 부호화하지 않습니다.또, 서버상에서 부호화된 스페이스로 해석됩니다(여기서 지적되고 있는 것처럼, URL-encode non-ASC 는 적절히 부호화되지 않습니다).II 문자).
다른 곳과 사이의 차이에 대한 좋은 설명이 있다.URI의 컴포넌트(예를 들어 쿼리 문자열 파라미터)로 안전하게 포함할 수 있도록 부호화하려면encodeURIComponent()
.
가장 좋은 답은 다음을 사용하는 것입니다.encodeURIComponent
쿼리 문자열의 값(다른 곳 없음)에 대해 설명합니다.
그러나 많은 API가 "+"를 "+"로 대체하기를 원하기 때문에 다음을 사용해야 했습니다.
const value = encodeURIComponent(value).replace('%20','+');
const url = 'http://example.com?lang=en&key=' + value
escape
에 따라 구현됩니다.encodeURI
많은 문자(# 나 짝수 / 등)를 부호화하지 않습니다.URI/URL: URI/URL: URI/URL: URI/URL: URI/URL: URI/URL: URI/URL: URI/URL: URI/URL: URI/URL: URI/URL.이것은 큰 도움이 되지 않고, 시큐어하지도 않습니다.
하는 것처럼 @Jochem은 @Jochem으로, @Jochem으로, @Jochem으로, @Jochem으로, @Jochem으로, @Jochem으로, @Jochem으로 하는 이 좋습니다.encodeURIComponent()
이름으로 어떤 로든 이러한 않는 것 (API).+
오래된 폴더명으로encodeURIComponent
잘 동작합니다.
예:
const escapedValue = encodeURIComponent(value).replace('%20','+');
const escapedFolder = encodeURIComponent('My Folder'); // no replace
const url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`;
qs npm 패키지를 사용하는 것이 좋습니다.
qs.stringify({a:"1=2", b:"Test 1"}); // gets a=1%3D2&b=Test+1
JS 오브젝트와 함께 사용하기 쉽고 모든 파라미터에 적절한 URL 인코딩을 제공합니다.
jQuery를 사용하고 있다면 method로 하겠습니다.이 URL은 오브젝트 매핑필드와 값을 부호화합니다.이것은 각 값에 대해 이스케이프 메서드를 호출하는 것보다 읽기 쉽습니다.
$.param({a:"1=2", b:"Test 1"}) // gets a=1%3D2&b=Test+1
최신 솔루션(2021년)
다른 답변이 작성되었기 때문에 URLearchParams API가 도입되었습니다.다음과 같이 사용할 수 있습니다.
const queryParams = { param1: 'value1', param2: 'value2' }
const queryString = new URLSearchParams(queryParams).toString()
// 'param1=value1¶m2=value2'
URL 이외의 문자도 인코딩합니다.
구체적인 예에서는 다음과 같이 사용합니다.
const myUrl = "http://example.com/index.html?param=1&anotherParam=2"; const myOtherUrl = new URL("http://example.com/index.html"); myOtherUrl.search = new URLSearchParams({url: myUrl}); console.log(myOtherUrl.toString());
encodeURIComponent()를 사용합니다.
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
단, php 버전과는 약간의 차이가 있다는 점에 유의하십시오.urlencode()
또한 @CMS에서 언급했듯이 모든 문자를 인코딩하지는 않습니다.http://phpjs.org/functions/urlencode/의 사람들은 js를 다음과 같이 만들었습니다.phpencode()
:
function urlencode(str) {
str = (str + '').toString();
// Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
// PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
return encodeURIComponent(str)
.replace('!', '%21')
.replace('\'', '%27')
.replace('(', '%28')
.replace(')', '%29')
.replace('*', '%2A')
.replace('%20', '+');
}
앞에서 설명한 바와 같이 URL을 인코딩하려면 다음 두 가지 기능이 있습니다.
encodeURI()
그리고.
encodeURIComponent()
두 가지 모두 존재하는 이유는 첫 번째가 URL을 유지하며 너무 많은 것을 이스케이프하지 않고 남길 위험이 있기 때문입니다.두 번째가 필요한 모든 것을 인코딩하기 때문입니다.
첫 번째 예에서는 새로 이스케이프된 URL을 주소 표시줄에 복사할 수 있습니다(예를 들어).그러나 이스케이프되지 않은 '&'는 필드 구분자를 방해하고, '='는 필드 이름과 값을 방해하며, '+'는 공백처럼 보입니다.단, 간단한 데이터의 경우, 이스케이프 대상의 URL 특성을 유지하고 싶을 때는 이 방법이 유효합니다.
두 번째는 문자열이 URL을 방해하지 않도록 하기 위해 필요한 모든 것입니다.중요하지 않은 여러 문자를 에스케이프하지 않고 그대로 두기 때문에 URL은 가능한 한 사람이 읽을 수 있는 상태로 유지됩니다.이렇게 인코딩된 URL은 이스케이프를 해제하지 않으면 URL로 기능하지 않습니다.
따라서 시간을 들일 수 있다면 항상 인코딩을 사용합니다.URIComponent() - 이름과 값의 쌍을 추가하기 전에 이 함수를 사용하여 이름과 값을 모두 인코딩한 후 쿼리 문자열에 추가합니다.
encodeURI()를 사용해야 하는 이유를 찾는 데 어려움을 겪고 있습니다.그건 똑똑한 사람들에게 맡기겠습니다.
2022년에는 정말 안전하기 위해 항상 인터페이스를 사용하여 URL을 구성하는 것을 고려해야 한다고 생각합니다.대부분의 일을 할 수 있을 거예요.그래서 당신의 코드에 따르면,
const baseURL = 'http://example.com/index.html';
const myUrl = new URL(baseURL);
myUrl.searchParams.append('param', '1');
myUrl.searchParams.append('anotherParam', '2');
const myOtherUrl = new URL(baseURL);
myOtherUrl.searchParams.append('url', myUrl.href);
console.log(myUrl.href);
// Outputs: http://example.com/index.html?param=1&anotherParam=2
console.log(myOtherUrl.href);
// Outputs: http://example.com/index.html?url=http%3A%2F%2Fexample.com%2Findex.html%3Fparam%3D1%26anotherParam%3D2
console.log(myOtherUrl.searchParams.get('url'));
// Outputs: http://example.com/index.html?param=1&anotherParam=2
아니면...
const params = new URLSearchParams(myOtherUrl.search);
console.log(params.get('url'));
// Outputs: http://example.com/index.html?param=1&anotherParam=2
이와 같은 것은 실패하지 않도록 보장된다.
일반 Javascript에서 시도했던 것과 비슷한 종류입니다.
function fixedEncodeURIComponent(str){
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
이중 인코딩을 방지하려면 인코딩 전에 URL을 디코딩하는 것이 좋습니다(예를 들어 사용자가 입력한 URL을 처리하는 경우, 이미 인코딩되어 있을 수 있습니다).
, 이렇게 ''가 있다고 칩시다.abc%20xyz 123
입력으로 입력(스페이스 1개가 이미 부호화되어 있습니다.
encodeURI("abc%20xyz 123") // wrong: "abc%2520xyz%20123"
encodeURI(decodeURI("abc%20xyz 123")) // correct: "abc%20xyz%20123"
URL 인코딩이란 무엇입니까?
URL 내에 특수 문자가 있는 경우 URL을 인코딩해야 합니다.다음은 예를 제시하겠습니다.
console.log(encodeURIComponent('?notEncoded=&+'));
" " " 를 제외한 모든 가 " " " 입니다.notEncoded
는 % 기호로 부호화되어 있습니다.URL 인코딩은 %로 모든 특수 문자를 이스케이프하기 때문에 퍼센트 인코딩이라고도 합니다.그런 다음 이 % 기호 뒤에 모든 특수 문자가 고유한 코드를 가집니다.
URL 인코딩이 필요한 이유:
특정 문자는 URL 문자열에 특수 값을 가집니다.예를 들어 ? 문자는 쿼리 문자열의 시작을 나타냅니다.웹에서 리소스를 성공적으로 찾으려면 문자가 문자열의 일부인지 URL 구조의 일부인지를 구분해야 합니다.
JS에서 URL 인코딩을 실현하려면 어떻게 해야 합니까?
JS는 URL을 쉽게 인코딩하기 위해 사용할 수 있는 많은 빌트인 유틸리티 기능을 제공합니다.다음의 2개의 편리한 옵션이 있습니다.
encodeURIComponent()
: 문자열을 URI의 컴포넌트를 인수로 사용하여 부호화된 URI 문자열을 반환합니다.encodeURI()
: 문자열을 URI를 인수로 사용하여 인코딩된 URI 문자열을 반환합니다.
예 및 경고:
스킴를 들어https를 URL "( 「 「」, 「https:/」)에 하지 않는 .encodeURIComponent()
이것은 실제로 기능하지 않는 URL로 변환할 수 있습니다.하다
// for a whole URI don't use encodeURIComponent it will transform
// the / characters and the URL won't fucntion properly
console.log(encodeURIComponent("http://www.random.com/specials&char.html"));
// instead use encodeURI for whole URL's
console.log(encodeURI("http://www.random.com/specials&char.html"));
를 URL에 할 수 .encodeURIComponent
닭고기이것에 의해, URL 가 올바르게 기능하지 않게 됩니다.
따라서 (이름에서 알 수 있듯이) 다음을 사용합니다.
encodeURIComponent
의의의 URL 。encodeURI
에에 URL 、 [URL]
하면 안 요.encodeURIComponent()
직접적으로.
RFC3986: Uniform Resource Identifier(URI; 유니폼자원 식별자): Generic 구문 보기
하위 항목 = "!" / "$" / "&" / "" "" / "(" / ")" / "*" / "+" / ";" / "="
예약된 문자의 목적은 URI 내의 다른 데이터와 구별할 수 있는 일련의 구분 문자를 제공하는 것입니다.
의 URI 는 RFC3986 ARE NOT URI에 의해 .encodeURIComponent()
.
RFC 3986(!, ', , 및 *를 예약)을 보다 엄격하게 준수하기 위해 이들 문자는 공식적인 URI 구분 용도가 없는 경우에도 다음 문자를 안전하게 사용할 수 있습니다.
MDN Web Docs 기능 사용...
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
난 아무 것도 안 먹혔어.제가 본 것은 로그인 페이지의 HTML 뿐입니다.이 HTML은 코드 200으로 클라이언트 측으로 돌아옵니다.(처음에는 로그인 페이지의 일반 텍스트를 로드하는 것이 아니라 다른 Ajax 요청 내에서 로그인 페이지를 로드하는 동일한 Ajax 요청입니다.)
로그인 컨트롤러에 다음 행을 추가했습니다.
Response.Headers["land"] = "login";
글로벌 Ajax 핸들러에서는 이렇게 했습니다.
$(function () {
var $document = $(document);
$document.ajaxSuccess(function (e, response, request) {
var land = response.getResponseHeader('land');
var redrUrl = '/login?ReturnUrl=' + encodeURIComponent(window.location);
if(land) {
if (land.toString() === 'login') {
window.location = redrUrl;
}
}
});
});
지금은 아무런 문제가 없고, 아주 잘 작동합니다.
URL 문자열 인코딩
var url = $(장소).attrsaughref'; // "URL" "/ "// url = ''; 또는onevar url = 'folder/index.folder'를 지정하시겠습니까?filename=#23d&noob=yes'; // "filename"
var encodedUrl = encodeURIComponent(url);
console.log(encodedUrl);
//outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes
for more info go http://www.sitepoint.com/jquery-decode-url-string
여기 라이브 데모가 있습니다.encodeURIComponent()
★★★★★★★★★★★★★★★★★」decodeURIComponent()
JS の js js :
<!DOCTYPE html>
<html>
<head>
<style>
textarea{
width:30%;
height:100px;
}
</style>
<script>
// encode string to base64
function encode()
{
var txt = document.getElementById("txt1").value;
var result = btoa(txt);
document.getElementById("txt2").value = result;
}
// decode base64 back to original string
function decode()
{
var txt = document.getElementById("txt3").value;
var result = atob(txt);
document.getElementById("txt4").value = result;
}
</script>
</head>
<body>
<div>
<textarea id="txt1">Some text to decode
</textarea>
</div>
<div>
<input type="button" id="btnencode" value="Encode" onClick="encode()"/>
</div>
<div>
<textarea id="txt2">
</textarea>
</div>
<br/>
<div>
<textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
</textarea>
</div>
<div>
<input type="button" id="btndecode" value="Decode" onClick="decode()"/>
</div>
<div>
<textarea id="txt4">
</textarea>
</div>
</body>
</html>
성능
오늘(2020.06.12) Chrome 83.0, Safari 13.1, Firefox 77.0 브라우저에서 MacOS HighSierra 10.13.6에서 선택한 솔루션에 대한 속도 테스트를 수행했습니다.이 결과는 대규모 URL 인코딩에 도움이 됩니다.
결론들
encodeURI
(B)가 가장 빠른 것 같지만 url-s에는 권장하지 않습니다.escape
솔루션(A)- MDN이 권장하는 솔루션 F는 중속입니다.
- 솔루션 D가 가장 느리다
세부 사항
솔루션 A B C D E F의 경우 두 가지 테스트를 수행합니다.
function A(url) {
return escape(url);
}
function B(url) {
return encodeURI(url);
}
function C(url) {
return encodeURIComponent(url);
}
function D(url) {
return new URLSearchParams({url}).toString();
}
function E(url){
return encodeURIComponent(url).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
function F(url) {
return encodeURIComponent(url).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
// ----------
// TEST
// ----------
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
[A,B,C,D,E,F]
.forEach(f=> console.log(`${f.name} ?url=${f(myUrl).replace(/^url=/,'')}`));
This snippet only presents code of choosen solutions
Chrome 결과 예시
esapi 라이브러리를 사용하여 아래 함수를 사용하여 URL을 인코딩할 수 있습니다.이 함수는 나머지 텍스트 내용이 인코딩되는 동안 '/'이(가) 인코딩으로 손실되지 않도록 보장합니다.
function encodeUrl(url)
{
String arr[] = url.split("/");
String encodedUrl = "";
for(int i = 0; i<arr.length; i++)
{
encodedUrl = encodedUrl + ESAPI.encoder().encodeForHTML(ESAPI.encoder().encodeForURL(arr[i]));
if(i<arr.length-1) encodedUrl = encodedUrl + "/";
}
return url;
}
https://www.owasp.org/index.php/ESAPI_JavaScript_Readme
fixedEncodeURIComponent
RFC 3986에 엄밀하게 준거하는 기능:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl).replace(/%20/g,'+');
인코딩된 ' '를 모두 바꾸려면 /g 플래그를 잊지 마십시오.
저는 항상 URL을 인코딩할 때 이것을 사용합니다.이것은 인코딩할 필요가 없어도 모든 문자를 인코딩하기 때문에 완전히 안전합니다.
function urlEncode(text) {
let encoded = '';
for (let char of text) {
encoded += '%' + char.charCodeAt(0).toString(16);
}
return encoded;
}
언급URL : https://stackoverflow.com/questions/332872/encode-url-in-javascript
'programing' 카테고리의 다른 글
Python pip 설치 실패: 잘못된 명령 eg_info (0) | 2022.10.29 |
---|---|
서브어레이를 열 값으로 그룹화하려면 어떻게 해야 합니까? (0) | 2022.10.29 |
캡슐화된 익명 함수 구문 설명 (0) | 2022.10.19 |
RowDataPacket 객체에 액세스하는 방법 (0) | 2022.10.19 |
왜 MariaDB의 CHECK 문은 Linux가 아닌 Windows에서 작동합니까? (0) | 2022.10.19 |