5

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

3 Answers 3

7

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I doubt very much that OP will find "ftpaddress" in a re-stringified integer. Something's fishy.
1

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>

1 Comment

Thank you so much! Didn't realize parseInt had this effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.