Javascript Function สำหรับการทำ URL Encode

ในบทความเรื่อง Cross site scripting ผมต้องการเครื่องมือที่จะทำการ url encode ที่ซึ่งจะสามารถแปลงตัวอักษรทุกตัวรวมทั้ง Alphanumeric characters ด้วยผมจึงการทำการค้นหาจาก google ก็พบ Javascript Url encoder/decode จาก www.webtoolkit.info ซึ่งรองรับ UTF-8 encoding ด้วย แต่ฟังก์ชันดังกล่าวก็ไม่ได้เข้ารหัสตัวอักษรทุกตัว ผมจึงต้อง ฟังก์ชันดังกล่าวได้ Javascript code ด้านล่าง

 function urlEncode(inputString, encodeAllCharacter){
       var outputString = '';
       if (inputString != null){
         for (var i = 0; i < inputString.length; i++ ){
            var charCode = inputString.charCodeAt(i);
            var tempText = "";
            if (charCode < 128) {
                if (encodeAllCharacter)
                {
                  var hexVal = charCode.toString(16);
                  outputString += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();  
                } else {
                  outputString += String.fromCharCode(charCode);
                }
                            
            } else if((charCode > 127) && (charCode < 2048)) {
                tempText += String.fromCharCode((charCode >> 6) | 192);
                tempText += String.fromCharCode((charCode & 63) | 128);
                outputString += escape(tempText);
            } else {
                tempText += String.fromCharCode((charCode >> 12) | 224);
                tempText += String.fromCharCode(((charCode >> 6) & 63) | 128);
                tempText += String.fromCharCode((charCode & 63) | 128);
                outputString += escape(tempText);
            }
         }
       }
       return outputString;
    }

ด้านล่างเป็นตัวอย่างโปรแกรมที่ผมเรียกใช้ฟังก์ชันดังกล่าวทดลองใช้งานกันได้ครับ

Plain Text:
Encode All Characters:
Encoded Text:

Code ที่คุณ Post มานี่ใช้งานได้ดีเลยครับ เป็นประโยชน์กับผมมาก ขอบคุณมากๆ เลยครับ

การทำ url encode คืออะไรหรอครับ

เด็กน้อยอยากรู้ด้วย...อิๆๆ

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><img> <object> <embed> <param>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.
ญาณรักข์ วรรณสาย