How to swap two characters in string by index with TypeScript

2 Answers

0 votes
function swap(str : string, left : number, right : number) {
    let arr = str.split('');
     
    let tmp = arr[left];
    arr[left] = arr[right];
    arr[right] = tmp;
     
    return arr.join('');
}
 
let str = "typescript";
 
str = swap(str, 1, 6);
 
console.log(str);
 
 
 
   
   
/*
run:
   
"trpescyipt" 
   
*/

 



answered Aug 24, 2022 by avibootz
0 votes
function swap(str : string, left : number, right : number) {
    return str.substring(0, left)
           + str[right]
           + str.substring(left + 1, right)
           + str[left]
           + str.substring(right + 1);
}
  
let str = "typescript";
  
str = swap(str, 1, 6);
  
console.log(str);
  
  
  
    
    
/*
run:
    
"trpescyipt" 
    
*/

 



answered Aug 24, 2022 by avibootz

Related questions

2 answers 164 views
3 answers 226 views
1 answer 158 views
1 answer 140 views
1 answer 263 views
1 answer 131 views
...