을 때 당신은 당신을 사용하여 탈출하는 대신 에 encodeuri/encodeURIComponent?

StackOverflow https://stackoverflow.com/questions/75980

문제

인코딩할 때에는 쿼리할 문자열을 전송한 웹 서버-할 때 사용 escape() 그 때 당신은 사용 encodeURI()encodeURIComponent():

사용 escape:

escape("% +&=");

사용 에 encodeuri()/encodeURIComponent()

encodeURI("http://www.google.com?var1=value1&var2=value2");

encodeURIComponent("var1=value1&var2=value2");
도움이 되었습니까?

해결책

탈출()

를 사용하지 않는다!escape() 에 정의된 섹션 B.2.1.2 탈출소개 텍스트의 부속서 B 말합니다:

...모든 언어의 기능 및 행동을 지정된 이 부속서에 있는 하나 이상 원하지 않는 특성과의 부재에서 기존 사용에서 제거 될 것이라이 사양에 있습니다....
...프로그래머를 사용하지 말아야 또는 가정의 존재 이 기능 및 행동을 할 때 쓰는 새로운 ECMAScript 코드....

행동:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape

특수 문자 인코딩을 가진 제외:@*_+-./

수 형태에 대한 문자,그의 코드 단위 값이 0xFF 이 두 자리를 탈출 시퀀스: %xx.

문자에 대한 더 중대한 코드 단위로그 형식 %uxxxx 사용됩니다.이 내에서 허용되지 않 query string(에서 정의 은 rfc3986 에):

query       = *( pchar / "/" / "?" )
pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded   = "%" HEXDIG HEXDIG
sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="

퍼센트 기호만 허용됩니다면 그것은 바로 다음에 두 개의 hexdigits,%가 다음 u 은 허용되지 않습니다.

에 encodeuri()

사용 에 encodeuri 할 때 원하는 작동하는 URL 이 있습니다.이 전화:

encodeURI("http://www.example.org/a file with spaces.html")

을 얻을:

http://www.example.org/a%20file%20with%20spaces.html

부르지 않 encodeURIComponent 것이기 때문에 파괴하는 URL 을 반환

http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html

encodeURIComponent()

사용 encodeURIComponent 하려는 경우 인코딩 가치의 URL 을 매개 변수입니다.

var p1 = encodeURIComponent("http://example.org/?a=12&b=55")

다음 URL 을 만들 필요:

var url = "http://example.net/?param1=" + p1 + "&param2=99";

당신이 완전한 URL:

http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&param2=99

Note encodeURIComponent 지 않을 탈출 ' 문자입니다.일반적인 버그를 사용하는 것 그것을 만들 html 등의 특성 href='MyUrl', 는 고통을 수 있는 사출 버그입니다.을 생성하는 경우에서 html 문자열을 사용하거나 "' 특성에 대한 인용 또는 추가 계층의 인코딩(' 로 인코딩할 수 있습%27).

에 대한 자세한 정보의 이 유형이 인코딩을 확인할 수 있습니다: http://en.wikipedia.org/wiki/Percent-encoding

다른 팁

의 차이 encodeURI()encodeURIComponent() 정확히 11 는 문자 인코딩된 encodeURIComponent 하지만 에 encodeuri:

Table with the ten differences between encodeURI and encodeURIComponent

내가 생성된 이 테이블은 쉽 console.테이블 Chrome 에서 이 코드:

var arr = [];
for(var i=0;i<256;i++) {
  var char=String.fromCharCode(i);
  if(encodeURI(char)!==encodeURIComponent(char)) {
    arr.push({
      character:char,
      encodeURI:encodeURI(char),
      encodeURIComponent:encodeURIComponent(char)
    });
  }
}
console.table(arr);

이 문서에서는 계몽:Javascript 광기:Query String 분석

나는 그것을 발견하려고 할 때 내 undersand 왜 decodeURIComponent 지 디코딩'+'습니다.여기 추출물입니다:

String:                         "A + B"
Expected Query String Encoding: "A+%2B+B"
escape("A + B") =               "A%20+%20B"     Wrong!
encodeURI("A + B") =            "A%20+%20B"     Wrong!
encodeURIComponent("A + B") =   "A%20%2B%20B"   Acceptable, but strange

Encoded String:                 "A+%2B+B"
Expected Decoding:              "A + B"
unescape("A+%2B+B") =           "A+++B"       Wrong!
decodeURI("A+%2B+B") =          "A+++B"       Wrong!
decodeURIComponent("A+%2B+B") = "A+++B"       Wrong!

encodeURIComponent 지 않는 인코딩 -_.!~*'(), 의 원인,문제에 게시 데이터를 php xml 문자열입니다.

예를 들어:
<xml><text x="100" y="150" value="It's a value with single quote" /> </xml>

일반적으로 탈출 encodeURI
%3Cxml%3E%3Ctext%20x=%22100%22%20y=%22150%22%20value=%22It's%20a%20value%20with%20single%20quote%22%20/%3E%20%3C/xml%3E

당신이 볼 수있는,하나의 견적을 인코딩되지 않습니다.문제를 해결 하려면 내가 만들어 두 가지 기능 문제를 해결하기 위해서는 프로젝트,인코딩을 위한 URL:

function encodeData(s:String):String{
    return encodeURIComponent(s).replace(/\-/g, "%2D").replace(/\_/g, "%5F").replace(/\./g, "%2E").replace(/\!/g, "%21").replace(/\~/g, "%7E").replace(/\*/g, "%2A").replace(/\'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29");
}

디코딩하기 위한 URL:

function decodeData(s:String):String{
    try{
        return decodeURIComponent(s.replace(/\%2D/g, "-").replace(/\%5F/g, "_").replace(/\%2E/g, ".").replace(/\%21/g, "!").replace(/\%7E/g, "~").replace(/\%2A/g, "*").replace(/\%27/g, "'").replace(/\%28/g, "(").replace(/\%29/g, ")"));
    }catch (e:Error) {
    }
    return "";
}

에 encodeuri()-탈출()함수에 대한 javascript 탈출하지 않 HTTP.

작은 비교 테이블 Java 대JavaScript 대PHP.

1. Java URLEncoder.encode (using UTF8 charset)
2. JavaScript encodeURIComponent
3. JavaScript escape
4. PHP urlencode
5. PHP rawurlencode

char   JAVA JavaScript --PHP---
[ ]     +    %20  %20  +    %20
[!]     %21  !    %21  %21  %21
[*]     *    *    *    %2A  %2A
[']     %27  '    %27  %27  %27 
[(]     %28  (    %28  %28  %28
[)]     %29  )    %29  %29  %29
[;]     %3B  %3B  %3B  %3B  %3B
[:]     %3A  %3A  %3A  %3A  %3A
[@]     %40  %40  @    %40  %40
[&]     %26  %26  %26  %26  %26
[=]     %3D  %3D  %3D  %3D  %3D
[+]     %2B  %2B  +    %2B  %2B
[$]     %24  %24  %24  %24  %24
[,]     %2C  %2C  %2C  %2C  %2C
[/]     %2F  %2F  /    %2F  %2F
[?]     %3F  %3F  %3F  %3F  %3F
[#]     %23  %23  %23  %23  %23
[[]     %5B  %5B  %5B  %5B  %5B
[]]     %5D  %5D  %5D  %5D  %5D
----------------------------------------
[~]     %7E  ~    %7E  %7E  ~
[-]     -    -    -    -    -
[_]     _    _    _    _    _
[%]     %25  %25  %25  %25  %25
[\]     %5C  %5C  %5C  %5C  %5C
----------------------------------------
char  -JAVA-  --JavaScript--  -----PHP------
[ä]   %C3%A4  %C3%A4  %E4     %C3%A4  %C3%A4
[ф]   %D1%84  %D1%84  %u0444  %D1%84  %D1%84

나는 사용하지 않는 것이 좋습니다 그 중 하나의 방법입니다.자신이 쓰는 않습니다.......

반은 주어진 좋은 예를 들어에 url 을 인코딩 아래와 같습니다.

var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);

console.log(header); 
// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"


function encodeRFC5987ValueChars (str) {
    return encodeURIComponent(str).
        // Note that although RFC3986 reserves "!", RFC5987 does not,
        // so we do not need to escape it
        replace(/['()]/g, escape). // i.e., %27 %28 %29
        replace(/\*/g, '%2A').
            // The following are not required for percent-encoding per RFC5987, 
            //  so we can allow for a little better readability over the wire: |`^
            replace(/%(?:7C|60|5E)/g, unescape);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

또한 기억들이 모두 인코딩을 가지 세트의 문자,그리고 하나를 선택해야 합니다.에 encodeuri()인코딩하는 몇몇 문자보다 encodeURIComponent(),인코딩하는 몇몇(또한 다른 dannyp 의 포인트)문자보다 탈출().

의 목적을 위해 인코딩을 자바스크립트는 주어진 세 개의 내장형 기능-

  1. 탈출()-하지 않는 인코딩 @*/+ 이 방법은 사용되지 않는 후 ECMA3 그래서 그것을 피해야 합니다.

  2. 에 encodeuri()-하지 않는 인코딩 ~!@#$&*()=:/,;?+' 가정 URI 에 완전한 URI,그렇지 않은 인코딩 예약 문자에서 특별한 의미를 갖는 URI.이 방법은 사용되는 경우는 것이 목적이 변환하는 완전한 URL 을 대신 특별한 세그먼트의 URL 이 있습니다.예 encodeURI('http://stackoverflow.com'); 을 줄 것- http://stackoverflow.com

  3. encodeURIComponent()-하지 않는 인코딩 - _ . ! ~ * ' ( ) 이 기능 인코딩하는 Uniform Resource Identifier(URI)구성 요소를 대체하여 각각의 인스턴스의 특정 문자에 의해 하나,둘,세 개 또는 네 개의 탈출 시퀀스를 나타내는 UTF-8 인코딩의 문자입니다.이 방법을 사용해야 하는지를 변환하는 구성 요소의 URL 이 있습니다.예를 들면 어떤 사용자 입력이 필요에 추가할 예 encodeURI('http://stackoverflow.com'); 을 줄 것-http%3A%2F%2Fstackoverflow.com

이 모든 인코딩을 수행에 UTF8i.전자 문자로 변환됩니다에 UTF-8 을 포맷입니다.

encodeURIComponent 다르 에 encodeuri 다는 점에서 인코딩 예약 문자와 숫자 등록하십시오#의 에 encodeuri

내가 찾는 실험으로 다양한 방법이 좋은 정신을 확인한 후에도 좋은 핸들의 그들의 다양한 용도와 기능이다.

끝으로 나는 발견 이 웹사이트 매우 유용한 확인을 의심하는 나는 뭔가를하고 적절하게.그것은 또한 검증된 유용한 디코딩하는 encodeURIComponent'ed 문자열 수 있는 오히려 도전적인 해석할 수 있습니다.한 책갈피는:

http://www.the-art-of-web.com/javascript/escape/

요한의 테이블, 나를 확장하기로 결정했다.내가 원하는 ASCII 문자 인코딩을 얻을.

screenshot of console.table

var ascii = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

var encoded = [];

ascii.split("").forEach(function (char) {
    var obj = { char };
    if (char != encodeURI(char))
        obj.encodeURI = encodeURI(char);
    if (char != encodeURIComponent(char))
        obj.encodeURIComponent = encodeURIComponent(char);
    if (obj.encodeURI || obj.encodeURIComponent)
        encoded.push(obj);
});

console.table(encoded);

표를 보면 인코딩된 자입니다.빈 세포는 원래 암호화된 문자가 동일합니다.


그냥을 추가,추가하는 또 다른 대한 테이블 urlencode()rawurlencode().유일한 차이 될 것으로 보인 인코딩의 공백 문자를 나타냅니다.

screenshot of console.table

<script>
<?php
$ascii = str_split(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", 1);
$encoded = [];
foreach ($ascii as $char) {
    $obj = ["char" => $char];
    if ($char != urlencode($char))
        $obj["urlencode"] = urlencode($char);
    if ($char != rawurlencode($char))
        $obj["rawurlencode"] = rawurlencode($char);
    if (isset($obj["rawurlencode"]) || isset($obj["rawurlencode"]))
        $encoded[] = $obj;
}
echo "var encoded = " . json_encode($encoded) . ";";
?>
console.table(encoded);
</script>

나는 이런 기능이 있어...

var escapeURIparam = function(url) {
    if (encodeURIComponent) url = encodeURIComponent(url);
    else if (encodeURI) url = encodeURI(url);
    else url = escape(url);
    url = url.replace(/\+/g, '%2B'); // Force the replacement of "+"
    return url;
};

수락 응답이 좋다.을 확장하에서 마지막 파트:

Note encodeURIComponent 않는'문자입니다.공통 버그를 사용하는 것 그것을 만들 html 과 같은 특성 href='MyUrl'는 고통을 수 있는 사출 버그입니다.을 생성하는 경우에서 html 문자열을 사용하거나"대신'을 특성 지수,또는 추가 층의 인코딩('로 인코딩할 수 있습%27).

하려는 경우 안전 측면에 %로 인코딩 예약되지 않은 캐릭터 인코딩되어야 합니다.

이 방법을 사용할 수 있습니다 그들을 탈출(소스 Mozilla)

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

// fixedEncodeURIComponent("'") --> "%27"

현대의 다시 작성@요한 echavarria 의 대답:

console.log(
    Array(256)
        .fill()
        .map((ignore, i) => String.fromCharCode(i))
        .filter(
            (char) =>
                encodeURI(char) !== encodeURIComponent(char)
                    ? {
                          character: char,
                          encodeURI: encodeURI(char),
                          encodeURIComponent: encodeURIComponent(char)
                      }
                    : false
        )
)

는 경우 또는 사용할 수 있습니다 테이블,대체 console.logconsole.table (에 대한 예뻐 출력).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top