<script type=”text/javascript”>
function stringLoopReplace()
{
str1 = document.form1.aaa.value;
str2 = document.form1.bbb.value;
document.body.innerHTML = document.body.innerHTML.replace(/str1/g,’str2’);
}
</script>
で本文のほうに
<FORM NAME=”form1”>
<INPUT TYPE=”text” NAME=”aaa” SIZE=10 VALUE=”平成”><P>
<INPUT TYPE=”text” NAME=”bbb” SIZE=10 VALUE=”昭和”><P>
<A href=”javascript:stringLoopReplace(’’,’’)”>置換</a>
</FORM>としてみたんですが、置換されません。 何を間違っているのか、教えていただけないでしょうか。
http://www.hatena.ne.jp/そのまま指定:detail]
見よう見まねなら、とりあえず
replace(/str1/g,’str2’);
を
replace(str1,str2);
に、あとはマニュアルなどを見てください。
http://www.tohoho-web.com/js/regexp.htm
正規表現(RegExp)
こういうふうに直してください。
変数名と、変数の内容の文字列とがごっちゃになっています。
function stringLoopReplace()
{
str1 = document.form1.aaa.value;
str2 = document.form1.bbb.value;
reg = new RegExp(str1, ”g”);
document.body.innerHTML = document.body.innerHTML.replace(reg,str2);
}
「文字列」と「変数」の使い方が誤っていますね。
> document.body.innerHTML.replace(/str1/g,’str2’);
ですと ”str1” という文字列が ”str2” という文字列に置換されてしまいます。
これは、JavaScript が「”(ダブルクォーテーション)」や「’(シングルクォーテーション)」
で囲まれた範囲を「文字列」として判断してしまう為です。
’str2’ … ”str2” という文字列
str2 … ”昭和” という文字列を保存している変数。
となります。
単純に str1 の内容を str2 の内容で置換したいのであれば、
document.body.innerHTML.replace( str1, str2 );
で OK です。
また、「/平成/g」という書き方ですが、実際には「正規表現オブジェクト」を表しています。
変数として正規表現オブジェクトを表す場合、
> re = new RegExp(”平成”, ”g”);
と表現する必要があります。
JavaScript の replace() 関数は、
> string.replace( 正規表現オブジェクト, 置換文字列 )
が正しい書き方ですので、replace() を使って置換する場合は、
> var str1 = document.form1.aaa.value;
> var str2 = document.form1.bbb.value;
> var re = new RegExp(str1, ”g”);
> document.body.innerHTML = document.body.innerHTML.replace( re, str2 );
が正しい書き方になります。
また、
> document.body.innerHTML = document.body.innerHTML.replace( new RegExp(str1, ”g”), str2 );
と、直接、replace() 関数内に書くことも可能です。
hatenaのシステムで半角のクォテーションが全角になっていると思いますが、適宜読み替えてください。
引数の渡し方などがおかしいです。修正したものを下記に書きます。
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=Shift_JIS”>
<title>置換</title>
<script type=”text/javascript”>
<!--
function stringLoopReplace(){
str_a = document.form1.aaa.value;
str_b = document.form1.bbb.value;
dl = document.body.innerHTML.split(str_a);
document.body.innerHTML = dl.join(str_b);
}
// -->
</script>
</head>
<body>
今年は平成17年です。去年は平成16年です。This is a pen.<p>
<FORM NAME=”form1”>
<INPUT TYPE=text NAME=aaa SIZE=10 VALUE=”平成”><P>
<INPUT TYPE=”text” NAME=bbb SIZE=10 VALUE=”昭和”><P>
<A href=”javascript:stringLoopReplace();”>置換</a>
</FORM>
</body>
</html>
Yahoo! JAPAN
(URLはダミーです)javascript:stringLoopReplace(’’,’’)
は引数を渡す必要はないので
javascript:stringLoopReplace()
で良いのではないでしょうか。
また、
document.body.innerHTML.replace(/str1/g,’str2’)
は
document.body.innerHTML.replace(/str1/g,str2)
で、シングルクォートでstr2をくくる必要はないかと。
シングルクォートでくくると、str2は変数ではなく、str2という文字列として認識されてしまうはずです。
みなさま、ありがとうございました!