How to empty a string in JS keeping the same object reference ?
var str= "hello";
str=""; // this will clear the string but will create a new reference
Strings are immutable (unchangable) so you can't do this. All operations that "modify" a string actually create a new/different string so the reference will be different.
Your type of problem is usually solved by having a string reference contained in an object. You pass the reference to the containing object and then you can change the string, but still have a reference to the new string.
var container = {
myStr: "hello";
};
container.myStr = "";
myFunc(container);
// myFunc could have modified container.myStr and the new value would be here
console.log(container.myStr)
This allows code, both before, during and after the myFunc()
function call to change container.myStr
and have that object always contain a reference to the latest value of the string.
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