2017-02-08 28 views
1

次のコードに問題があります。文字列を別の文字列に置き換えて、imgコードを生成したい。しかし、エラーメッセージ「str.replace is not a function」が表示されます。どんな考え?Javascript replace関数 "関数ではありません"

<input type="text" id="text"> 
    <input type="button" value="See Code" onclick="myFunction();"> 
    <input type="text" id="code" name="code"> 

<script> 
    function myFunction() { 
     var str = parseInt(document.getElementById("text").value); 
     var res = str.replace("ftpadress", "htmladress"); 
     var code = str.concat("<img src='",res,"' width='100%'>"); 
     document.getElementById("code").value = code; 
     } 
</script> 
+2

でいいと思う

'str'それは' number'だ、 'parseInt'の結果である、そう。 ['.replace()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)はStringメソッドです。 – mrlew

+0

[.replaceが関数ではないというエラーメッセージが表示されるのはなぜですか?](http://stackoverflow.com/questions/3141337/why-do-i-get-an-error-message-that- – Xufox

+0

文字列 '' ftpadress ''を含む可能性のある値に対して' 'parseInt()'を呼び出すのはなぜですか? – nnnnnn

答えて

2

、 strが、それは数だ、のparseIntの結果である、そう。 .replace()はStringメソッドです。

私が正しく理解している場合は、文字列を置き換えてコードを取得し、新しい文字列とコードで画像タグを生成したいと考えています。私は...

< input type = "text" 
 
id = "text" > 
 
    < input type = "button" 
 
value = "See Code" 
 
onclick = "myFunction();" > 
 
    < input type = "text" 
 
id = "code" 
 
name = "code" > 
 

 
    <script> 
 
    function myFunction() { 
 
    //changed 
 
    var str = document.getElementById("text").value; //get text 
 
    var res = str.replace("ftpadress", "htmladress"); //replace 
 
    var code = parseInt(str).toString(); //get code and cast it back to text 
 
    document.getElementById("code").value = code; //insert code 
 
    var withTag = code.concat("<img src='", res, "' width='100%'>"); //generate tag 
 
    } < /script>

+0

ありがとう!あなたの解決策も素晴らしいです。 – Flo

0

のparseIntは、整数を返していない文字列あなたは、あなたがキャストする必要があります)(str.replaceを使用することはできませんので、それ最初

だけ追加STR = str.toString();置換機能を使用する前に

+0

私は、OPが "ftpaddress"を再文字列化された整数で見つけることは間違いありません。何か怪しいです。 – Amadan

1

キャスト(parseInt関数)を削除するだけで、すべて正常に動作するはずです。コメント@mrlewとして

<input type="text" id="text"> 
    <input type="button" value="See Code" onclick="myFunction();"> 
    <input type="text" id="code" name="code"> 

<script> 
    function myFunction() { 
     //changed 
     var str = document.getElementById("text").value; 
     console.log(str); 
     var res = str.replace("ftpadress", "htmladress"); 
     var code = str.concat("<img src='",res,"' width='100%'>"); 
     document.getElementById("code").value = code; 
     } 
</script> 
+0

ありがとうございました! parseIntがこの効果を持っていることを認識していませんでした。 – Flo

関連する問題