I am not really sure why the replace doesn’t work in my code.
Here is the code:
var x = "counting..."
function process(element){
if(element.substr(element.length-3) == "..."){
element.toString().replace("...","");
console.log("works")
}
else{
element +='.'
}
}
process(x)
setInterval(function(){console.log(x)},500)
In the above example, my code will console it works, but the replace function will not change the ... to nothing.
Could anyone explain to me why this happens and give me a better solution?
>Solution :
You pass element=xto the function, then use .toString(). This creates and returns another string, which is then acted upon by replace, which returns yet another string. You don’t store the result anywhere, nor return it. It simply gets lost.
What you want to do instead is:
function process(str) {
if (str.endsWith("..."))
return str.substring(0, str.length - 3);
return str + "."
}
x = process(x)
Note that I used .substring() to remove the last 3 characters since you already checked that the string ends with "...". If you use .replace() you run another unnecessary search and you also risk deleting some other occurrence of "..." in the middle of the string instead of the last one.
Also note that in the last line I am doing x = process(x), otherwise x will keep its value since .substring() (like .replace()) just returns a new string and does not modify the original.
See also the doc: