1

Im trying to replace the first '0' in index 0 of the array I made called 'bits'.

bits = ['01010'];

console.log(bits[0].charAt(1));

bits[0].charAt(0) = '9'; // <-Not working

console.log(bits[0].charAt(0));

What would I replace the third line of code with above to accomplish this?

The final console log should return '9'

(JSBIN link)

Also str.replaceAt doesnt work as well

Ghoyos
  • 604
  • 2
  • 7
  • 18
  • Why? Why not a nested array or a number? – Jonas Wilms Feb 08 '18 at 20:58
  • 1
    Possible duplicate of [How do I replace a character at a particular index in JavaScript?](https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript) – juvian Feb 08 '18 at 20:58
  • 3
    Strings are immutable. Even if that statement had been `bits[0][0] = '9'`, the assignment would have been a no-op in non-strict mode and thrown a `TypeError` in strict mode. – Patrick Roberts Feb 08 '18 at 20:59
  • 1
    charAt is a function that return a value. You cannot assign a value to it. – floverdevel Feb 08 '18 at 21:00
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Character_access – axiac Feb 08 '18 at 21:02

3 Answers3

4
 bits[0] = "9" + bits[0].substr(1);

Alternatively you can write a replace function:

function replace(str, replace, start, end){
  return str.substr(0, start) + replace + str.substr(end || start + replace.length);
}

bits[0] = replace(bits[0], "9", 0);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

make a copy of string to replace any character . also a custom function "setCharAt" needs to be defined

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

after declaring the functions execute below given code to replace character at "0" index

bits[0]=setCharAt(bits[0],0,9)

after doing this final console.log will return "9"

Khan M
  • 415
  • 3
  • 17
1
var bits = ['01010'];
console.log(bits); //["01010"]
bits[0] = bits[0].replace('0','9');
console.log(bits); //["91010"]
Bassem Rabia
  • 206
  • 2
  • 7