Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace function doesn't replace the word

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading