Replace a character c1 with c2 and c2 with c1 in a string S | Javascript program to replace c1 with c2 and c2 with c1 ; loop to traverse in the string ; check for c1 and replace ; check for c2 and replace ; Driver code
function replace ( s , c1 , c2 ) { let l = s . length ; let arr = s . split ( " " ) ; for ( let i = 0 ; i < l ; i ++ ) { if ( arr [ i ] == c1 ) arr [ i ] = c2 ; else if ( arr [ i ] == c2 ) arr [ i ] = c1 ; } return arr . join ( " " ) ; } let s = " " ; let c1 = ' ' , c2 = ' ' ; document . write ( replace ( s , c1 , c2 ) ) ;