-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm7.html
More file actions
35 lines (23 loc) · 1.18 KB
/
algorithm7.html
File metadata and controls
35 lines (23 loc) · 1.18 KB
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
31
32
33
34
35
<!DOCTYPE html>
<html>
<body>
<script>
//https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace
//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. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog"
//check the case of 1st letter in a target word
function myReplace(str, before, after) {
var regex = new RegExp(before, 'gi');
var position = str.search(regex);
if (str[position].match(/[a-x]/) ) {
return str.replace(regex, after[0].toLowerCase().concat(after.substr(1)));
} else return str.replace(regex, after[0].toUpperCase().concat(after.substr(1)));
}
//tests
console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));
console.log(myReplace("Let us go to the store", "store", "mall"));
console.log(myReplace("His name is Tom", "Tom", "john"));
console.log(myReplace("Let us get back to more Coding", "coding", "algorithms"));
</script>
</body>
</html>