[英]Uncaught TypeError: Cannot read properties of undefined (reading 'replace'). I am facing this error in my site
I am using this code on the WordPress website and errors continuously coming to my site.我在 WordPress 网站上使用此代码,并且错误不断出现在我的网站上。
<script>
function setNiceResult(valor, id){
var div = $("#"+id);
valor = valor.replace(/\{\{/g, "<strong class=\"fuerte\">").replace("}}", "</strong>");
valor = valor.replace(/\}\}/g, "</strong>");
valor = valor.replace(/\{/g, "<strong class=\"medio\">").replace("}", "</strong>");
valor = valor.replace(/\}/g, "</strong>");
div.html(valor);
window.redrawMasonry(); // NO BORRAR!
}
</script>
The reason why you are receiving this error is because the variable valor does not have a value assigned to it and thus is undefined
.您收到此错误的原因是因为变量 valor 没有分配给它的值,因此是undefined
。
replace()
is a function that acts on string
values. replace()
是一个作用于string
值的函数。
PROBLEM:问题:
var sentence; // value is undefined sentence = sentence.replace("word", "new word"); // trying to execute replace function in undefined type console.log("sentence: ", sentence);
Solution 1: To prevent the error from occuring, you can assign an empty string value.解决方案1:为防止发生错误,您可以分配一个空字符串值。
var sentence = ''; // value is undefined sentence = sentence.replace("word", "new word"); // trying to execute replace function in undefined type console.log("sentence: ", sentence);
Solution 2:解决方案2:
You can use a ?
你可以使用一个?
optional chaining operator to only execute replace function if the value is not undefined
:可选链接运算符仅在值undefined
时才执行替换功能:
var sentence; sentence = sentence?.replace("word", "new word"); console.log("sentence: ", sentence); var anotherSentence = "Some word value"; anotherSentence = anotherSentence?.replace("word", "new word"); console.log("anotherSentence: ", anotherSentence);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.