JavaScriptでのURLデコードはこちらの記事を参照してください。
encodeURIComponent
メソッドを利用します。<!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 encodeStr = encodeURIComponent(inputStr);
var out_elem = document.getElementById("outputText");
out_elem.value = encodeStr;
}
</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タグの要素(テキストボックス)を取得します。 var in_elem = document.getElementById("inputText");
var inputStr = in_elem.value;
encodeURIComponent
メソッドに与えてURLエンコードをします。エンコード結果はencodeURIComponent
メソッドの
戻り値として返ります。 var encodeStr = encodeURIComponent(inputStr);
var out_elem = document.getElementById("outputText");
out_elem.value = encodeStr;
http://www.ipentec.com/search?query=C++andC#
の文字列を入力テキストボックスに入力します。+
の文字や #
の文字はURLでは特殊な文字として扱われるため、URL、またはURLのパラメーターには利用できない文字になります。このため、記号部分はURLエンコードの必要があります。http://www.ipentec.com/search?query=C++andC#
の文字列は http%3A%2F%2Fwww.ipentec.com%2Fsearch%3Fquery%3DC%2B%2BandC%23
の文字列に変換されます。encodeURIComponent
メソッドでエンコードします。C++andC#
をencodeURIComponent
メソッドでエンコードし、http://www.ipentec.com/search?query=
のURLのqueryパラメーターの値として設定し、http://www.ipentec.com/search?query=C%2B%2BandC%23
という文字列を作成します。