The current ‘Advanced’ solution:
- doesn’t address the constraints of the question
- doesn’t use ‘advanced’ features of JS
- doesn’t provide a more concise solution
- introduces potential bugs/edge cases (ex before/after are different lengths).
In short, it answers a question that isn’t being asked. The ‘good’ parts of this answer are the application of regular expressions via RegExp.test() and string.replace(). Why not use a solution that puts more emphasis on those.
Here’s a solution that leverages the full capabilities of Regex to provide a very concise answer.
function myReplace(str, before, after) {
var isTitleCase = /^[A-Z]/.test(before);
after = (isTitleCase)
? after[0].toUpperCase() + after.slice(1)
: after[0].toLowerCase() + after.slice(1);
return str.replace(before, after);
}
-
The ^ selector allows the regex to operate from the start of the string, and absent expansion operators (ie *, +) the capital alpha selector [A-Z] only applies to the first char. Many of the proposed solutions extract the first char (ie before[0]), instead of using the built-in capabilities of RegEx.
-
The ternary operator is a bit ‘advanced’ but provides a very useful shortcut to apply quick transforms depending on a bool state.
-
This version keeps string mutation (ie string recreation) to a minimum. The ternary operator creates 3 (ie 1st char of after, the rest of after, the concatenated form of after) strings, replace creates 1.
-
It takes a ridiculously tiny amount of code using RegEx vs the non-RegEx alternatives.
Here’ s another, more advanced but slightly less concise, solution.
function myReplace(str, before, after) {
var isTitleCase = /^[A-Z]/.test(before);
after = (isTitleCase)
? after.replace(/^[A-Za-z]/, after.match(/^[A-Za-z]/)[0].toUpperCase())
: after.replace(/^[A-Za-z]/, after.match(/^[A-Za-z]/)[0].toLowerCase());
return str.replace(before, after);
}
Works the same as the 1st solution except it uses RegEx to rebuilt the ‘after’ string.
-
RegEx.match() is used to extract the first letter
-
RegEx.replace() us used to swap the first letter
-
The upper/lower matching demonstrates how to capture in a case-insensitive way.
-
The number of mutations is the same.
Note: We could just apply .toLowerCase() on ‘after’ if it isn’t title-case but these answers assume the question is looking to maintain the title-case only.
Anyway, it looked like there was some room for improvement. Learning RegEx can be extremely difficult without good examples. I thought this might be a good place to present one.