I am using this code on the WordPress website and errors continuously coming to my site.
JavaScript
x
12
12
1
<script>
2
function setNiceResult(valor, id){
3
var div = $("#"+id);
4
valor = valor.replace(/{{/g, "<strong class="fuerte">").replace("}}", "</strong>");
5
valor = valor.replace(/}}/g, "</strong>");
6
valor = valor.replace(/{/g, "<strong class="medio">").replace("}", "</strong>");
7
valor = valor.replace(/}/g, "</strong>");
8
div.html(valor);
9
window.redrawMasonry(); // NO BORRAR!
10
}
11
</script>
12
Advertisement
Answer
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
.
replace()
is a function that acts on string
values.
PROBLEM:
JavaScript
1
3
1
var sentence; // value is undefined
2
sentence = sentence.replace("word", "new word"); // trying to execute replace function in undefined type
3
console.log("sentence: ", sentence);
Solution 1: To prevent the error from occuring, you can assign an empty string value.
JavaScript
1
3
1
var sentence = ''; // value is undefined
2
sentence = sentence.replace("word", "new word"); // trying to execute replace function in undefined type
3
console.log("sentence: ", sentence);
Solution 2:
You can use a ?
optional chaining operator to only execute replace function if the value is not undefined
:
JavaScript
1
9
1
var sentence;
2
sentence = sentence?.replace("word", "new word");
3
console.log("sentence: ", sentence);
4
5
6
7
var anotherSentence = "Some word value";
8
anotherSentence = anotherSentence?.replace("word", "new word");
9
console.log("anotherSentence: ", anotherSentence);