-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch-and-replace.js
More file actions
30 lines (20 loc) · 816 Bytes
/
search-and-replace.js
File metadata and controls
30 lines (20 loc) · 816 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
Perform a search and replace on the sentence using the arguments provided and return
the new sentence.
First argument is the sentence to perform the search and replace on.
Second argument is the word that you will be replacing (before).
Third argument is what you will be replacing the second argument with (after).
Note
Preserve the case of the first character in the original word when you are replacing it.
For example if you mean to replace the word "Book" with the word "dog",
it should be replaced as "Dog"
*/
function myReplace(str, before, after) {
let regex = /^[A-Z]/;
if (regex.test(before)) {
after = after.charAt(0).toUpperCase() + after.slice(1);
}
str = str.replace(before, after);
return str;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");