How to replace a character at a specific index in a string with Node.js

2 Answers

0 votes
String.prototype.replaceAt = function(i, replacement) {
    return this.substr(0, i) + replacement + this.substr(i + replacement.length);
}
  
let s = "node.js php python c++";
  
s = s.replaceAt(2, "X"); 
console.log(s);
  
  
s = s.replaceAt(13, "Z"); 
console.log(s);
  
  
s = s.replaceAt(16,  ' '); 
console.log(s); 
 
 
 
  
  
/*
run:
  
noXe.js php python c++
noXe.js php pZthon c++
noXe.js php pZth n c++
 
*/

 



answered Jul 4, 2022 by avibootz
0 votes
String.prototype.replaceAt = function(i, replacement) {
    let arr = this.split("");
    arr[i] = replacement;
    return arr.join("");
}

let s = "node.js php python c++";
  
s = s.replaceAt(2, "X"); 
console.log(s);
  
  
s = s.replaceAt(13, "Z"); 
console.log(s);
  
  
s = s.replaceAt(16,  ' '); 
console.log(s); 
 
 
 
  
  
/*
run:
  
noXe.js php python c++
noXe.js php pZthon c++
noXe.js php pZth n c++
 
*/

 



answered Jul 4, 2022 by avibootz

Related questions

1 answer 170 views
1 answer 168 views
1 answer 171 views
...