Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace function "is not a function"

Tags:

javascript

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>
like image 833
Flo Avatar asked Feb 08 '17 01:02

Flo


People also ask

What is replace () in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

Why replaceAll is not working in JS?

The "replaceAll" is not a function error occurs when we call the replaceAll() method on a value that is not of type string, or in a browser that doesn't support it. To solve the error, only call the replaceAll() method on strings in supported browsers. Here is an example of how the error occurs. Copied!

Does JavaScript replace replace all?

The replaceAll() method will substitute all instances of the string or regular expression pattern you specify, whereas the replace() method will replace only the first occurrence.

What is difference between replace and replaceAll in JavaScript?

3.1 The difference between replaceAll() and replace() If search argument is a string, replaceAll() replaces all occurrences of search with replaceWith , while replace() only the first occurence. If search argument is a non-global regular expression, then replaceAll() throws a TypeError exception.


1 Answers

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>
like image 121
Karuhanga Avatar answered Sep 28 '22 04:09

Karuhanga