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:
@@ -76,17 +76,15 @@ myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
|
||||
|
||||
```javascript
|
||||
function myReplace(str, before, after) {
|
||||
//Create a regular expression object
|
||||
var re = new RegExp(before, "gi");
|
||||
//Check whether the first letter is uppercase or not
|
||||
if (/[A-Z]/.test(before[0])) {
|
||||
//Change the word to be capitalized
|
||||
after = after.charAt(0).toUpperCase() + after.slice(1);
|
||||
// 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
|
||||
if (/^[A-Z]/.test(before)) {
|
||||
after = after[0].toUpperCase() + after.substr(1)
|
||||
} else {
|
||||
after = after[0].toLowerCase() + after.substr(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
|
||||
@@ -95,11 +93,10 @@ myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
|
||||
|
||||
#### Code Explanation
|
||||
|
||||
* In this solution, regular expression `[A-Z]` is used to check if character is uppercase.
|
||||
* Create a new regular expression object, **re**.
|
||||
* In this solution, regular expression `^[A-Z]` is used to check (test) if the first character of **before** is uppercase.
|
||||
* If first letter of **before** is capitalized, change the first letter of **after** to uppercase.
|
||||
* Replace **before** with **after** in the string.
|
||||
* Return the new string.
|
||||
* Else: If first letter of **before** is lowercase, change the first letter of **after** to lowercase
|
||||
* Return the new string replacing **before** with **after**.
|
||||
|
||||
#### Relevant Links
|
||||
|
||||
|
Reference in New Issue
Block a user