Flo
Flo

Reputation: 209

Javascript replace function "is not a function"

I have an issue with the following code. I want to replace a string by another one, and generate an img code. However, I got an error message: str.replace is not a function. Any idea why?

    <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>

Upvotes: 5

Views: 37795

Answers (3)

karuhanga
karuhanga

Reputation: 3322

As @mrlew pointed out, str is result of parseInt and therefore, it's a number. replace() is a string method, so it will not work on a number.

If I understood correctly, you would like to replace a string, retrieve a code and then generate an image tag with the new string and code.

I'd go with...

<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 a string
    document.getElementById("code").value = code; //insert code
    var withTag = code.concat("<img src='", res, "' width='100%'>"); //generate tag
}
</script>

Upvotes: 7

iwaduarte
iwaduarte

Reputation: 1700

Just remove the casting (parseInt function) and everything should work fine.

 <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>

Upvotes: 1

Fady Sadek
Fady Sadek

Reputation: 1140

parseInt returns an integer not a string so you can not use str.replace() , you need to cast it first

just add str = str.toString(); before using the replace function

Upvotes: 1

Related Questions