Replace two substrings ( of a string ) with each other | Function to return the resultant string ; Iterate through all positions i ; Current sub - string of length = len ( A ) = len ( B ) ; If current sub - string gets equal to A or B ; Update S after replacing A ; Update S after replacing B ; Return the updated string ; Driver code
function updateString ( S , A , B ) { let l = A . length ; for ( let i = 0 ; i + l <= S . length ; i ++ ) { let curr = S . substring ( i , i + l ) ; if ( curr == A ) { let new_string = S . substring ( 0 , i ) + B + S . substring ( i + l ) ; S = new_string ; i += l - 1 ; } else { let new_string = S . substring ( 0 , i ) + A + S . substring ( i + l ) ; S = new_string ; i += l - 1 ; } } return S ; } let S = " " ; let A = " " ; let B = " " ; document . write ( updateString ( S , A , B ) ) ;