How to swap characters in string by index in JavaScript

2 Answers

0 votes
String.prototype.replaceAt=function(index, ch) {
    return this.substr(0, index) + ch + this.substr(index + ch.length);
}
   
s = "abcd"; 

var tmp = s[0];
s = s.replaceAt(0, s[3]);
s = s.replaceAt(3, tmp);

document.write(s);  
 


/*
run:
    
dbca
    
*/

 



answered Jun 21, 2019 by avibootz
0 votes
String.prototype.replaceAt=function(index, ch) {
    return this.substr(0, index) + ch + this.substr(index + ch.length);
}

function swap(s, index1, index2) {
    var tmp = s[index1];
    s = s.replaceAt(index1, s[index2]);
    s = s.replaceAt(index2, tmp);
    
    return s;
}

    
s = "ayzd"; 
 
s = swap(s, 2, 3);
 
document.write(s);  
  
 
 
/*
run:
     
aydz 
     
*/

 



answered Jun 21, 2019 by avibootz

Related questions

3 answers 237 views
2 answers 173 views
2 answers 179 views
1 answer 164 views
1 answer 149 views
1 answer 274 views
1 answer 189 views
...