fix(guide): update "Search and Replace" intermediate solution (#36366)

new solution addresses the possibility of first letter of arg "before" being lower case and needing to change the first letter of "after" from capital to lowercase

solution more streamlined

added resource to help with regular expressions
This commit is contained in:
Jesse Rykerson
2019-07-24 10:31:35 -04:00
committed by mrugesh
parent dd3c0e0893
commit 284db50f47

View File

@@ -76,17 +76,15 @@ myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
```javascript ```javascript
function myReplace(str, before, after) { function myReplace(str, before, after) {
//Create a regular expression object // Check if first character of argument "before" is a capital or lowercase letter and change the first character of argument "after" to match the case
var re = new RegExp(before, "gi"); if (/^[A-Z]/.test(before)) {
//Check whether the first letter is uppercase or not after = after[0].toUpperCase() + after.substr(1)
if (/[A-Z]/.test(before[0])) { } else {
//Change the word to be capitalized after = after[0].toLowerCase() + after.substr(1)
after = after.charAt(0).toUpperCase() + after.slice(1);
} }
//Replace the original word with new one
var newStr = str.replace(re, after);
return newStr; // return string with argument "before" replaced by argument "after" (with correct case)
return str.replace(before, after);
} }
// test here // test here
@@ -95,11 +93,10 @@ myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
#### Code Explanation #### Code Explanation
* In this solution, regular expression `[A-Z]` is used to check if character is uppercase. * In this solution, regular expression `^[A-Z]` is used to check (test) if the first character of **before** is uppercase.
* Create a new regular expression object, **re**.
* If first letter of **before** is capitalized, change the first letter of **after** to uppercase. * If first letter of **before** is capitalized, change the first letter of **after** to uppercase.
* Replace **before** with **after** in the string. * Else: If first letter of **before** is lowercase, change the first letter of **after** to lowercase
* Return the new string. * Return the new string replacing **before** with **after**.
#### Relevant Links #### Relevant Links