JavaScriptでのURLエンコードはこちらの記事を参照してください。
JavaScriptでURLをデコードするコードを紹介します。
JavaScriptでURLをデコードする処理をしたい場合があります。
JavaScriptでURLをエンコードするにはdecodeURIComponent
メソッドを利用します。
以下のHTMLファイルを作成します。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
function buttonClick() {
var in_elem = document.getElementById("inputText");
var inputStr = in_elem.value;
var decodeStr = decodeURIComponent(inputStr);
var out_elem = document.getElementById("outputText");
out_elem.value = decodeStr;
}
</script>
</head>
<body>
入力:<input type="text" id="inputText" style="width:80%;" /><br />
<input type="button" onclick="buttonClick();" value="Exec" /><br />
出力:<input type="text" id="outputText" style="width:80%;" />
</body>
</html>
document.getElementById
メソッドを呼び出し、idが"inputText"であるinputタグの要素(テキストボックス)を取得します。
取得したテキストボックスのvalueの値を参照してテキストボックスに入力された文字列を取得します。
テキストボックスの文字列取得の詳細はこちらの記事を参照して下さい。
var in_elem = document.getElementById("inputText");
var inputStr = in_elem.value;
テキストボックスに入力されている文字列をdecodeURIComponent
メソッドに与えてURLエンコードをします。エンコード結果はdecodeURIComponent
メソッドの
戻り値として返ります。
var decodeStr = decodeURIComponent(inputStr);
URLエンコードされた文字列をIDが"outputText"のinputタグの要素 (テキストボックス)に表示します。
var out_elem = document.getElementById("outputText");
out_elem.value = decodeStr;
上記のHTMLファイルをWebブラウザで開きます。下図のページが表示されます。
URLエンコードされた文字列を[入力]テキストボックスに入力します。
[Exec]ボタンをクリックします。[入力]のテキストボックスに入力された文字列をURLデコードし、
デコードされた文字列を[出力]テキストボックスに表示します。