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>
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.
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!
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With