Ghoyos
Ghoyos

Reputation: 622

Im trying to replace a particular char within an index of an array.

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

Upvotes: 1

Views: 56

Answers (3)

Khan M
Khan M

Reputation: 415

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"

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138457

 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);

Upvotes: 4

Bassem Rabia
Bassem Rabia

Reputation: 226

var bits = ['01010'];
console.log(bits); //["01010"]
bits[0] = bits[0].replace('0','9');
console.log(bits); //["91010"]

Upvotes: 1

Related Questions