0

I am trying to replace the 8th character in each element of an array. I know JavaScript does not have a built-in function to replace string characters. I was able to find to potentially helpful code on this site. They accept strings as parameters, but when I pass in a array such as cookies[0], it does not change anything in the string. Why is that? Is there a way I can get this to work? Thanks in advance for any help.

var cookies = ["cartItem1", "cartItem2", "cartItem3", "cartItem4"];

function setCharAt(str,index,chr) {
    if(index > str.length-1) return str;
    return str.substr(0,index) + chr + str.substr(index+1);
}

function delCookie(){
    cookies.splice(0,1);
    setCharAt(cookies[0], 8, "Z");

}

delCookie();

I also tried it this way:

var cookies = ["cartItem1", "cartItem2", "cartItem3", "cartItem4"];


String.prototype.replaceAt=function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
};

function delCookie2(){
    cookies.splice(0,1);
    cookies[0].replaceAt(8, "Z");
}

delCookie2();
1
  • Additional information about the answers given: In JavaScript, strings are immutable, which means that they cannot be changed -- ever. They can only be replaced. Commented May 3, 2014 at 13:39

2 Answers 2

2

Both your methods (setCharAt and replaceAt) are returning the result, which means you have to set it:

function delCookie() {
   cookies.splice(0,1);
   cookies[0] = cookies[0].replaceAt(8, "Z"); 
   //or
   // cookies[0] = setCharAt(cookies[0], 8, "Z");
}
Sign up to request clarification or add additional context in comments.

Comments

0

The "setCharAt" function doesn't actually alter the string passed in - it returns a new string with the appropriate character changed. In order to get the behavior you want, you'll have to replace the old string in your array with the new one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.