searchAndReplace

Medium · String Manipulations · 2 test cases

Perform a search and replace on the sentence using the arguments provided and return the new sentence. Preserve the case of the first character in the original word when you are replacing it.

Examples

searchAndReplace('He is Sleeping on the couch', 'Sleeping', 'sitting') → 'He is Sitting on the couch'

Starter code

function searchAndReplace(str, before, after) {

}

Complexity of the optimal solution

Time O(n), space O(n). The `replace` method may need to scan the entire string (length n) to find the word to replace. Creating the new string also requires O(n) time and space.

Solve searchAndReplace in the browser