Find and Replace all occurrence of a substring in the given String | Function to replace all the occurrences of the sublet S1 to S2 in let S ; Stores the resultant let ; Traverse the let s ; If the first character of let s1 matches with the current character in let s ; If the complete let matches or not ; If complete let matches then replace it with the let s2 ; Otherwise ; Otherwise ; Print the resultant let ; Driver Code
function modifylet ( s , s1 , s2 ) { let ans = " " ; for ( let i = 0 ; i < s . length ; i ++ ) { let k = 0 ; if ( s [ i ] == s1 [ k ] && i + s1 . length <= s . length ) { let j ; for ( j = i ; j < i + s1 . length ; j ++ ) { if ( s [ j ] != s1 [ k ] ) { break ; } else { k = k + 1 ; } } if ( j == i + s1 . length ) { ans = ans + s2 ; i = j - 1 ; } else { ans = ans + s [ i ] ; } } else { ans = ans + s [ i ] ; } } document . write ( ans ) ; } let S = " " ; let S1 = " " ; let S2 = " " ; modifylet ( S , S1 , S2 ) ;