Search and Replace (Short Solution)

Wanna share my solution to this specific problem. I personally think the example solutions are somehow very long and its difficult to get a overview of the solution. I also like to keep things short so the RegExp is build using the class constructor “new” (credits to: and the second part is a function with the tertiary operator (? : ).
That way the solution is basically a one-liner, which is just formatted to be more readable.

I check the solution in the hints sometimes (after i solved it of course) and in this case my minimized solution is very different form these examples. Here my solution in case it could be useful for other FFCamper.
Also curious on why aiming for a more “complex” solution and not keeping it simple in this example?
Knowing that the new operator might be new to some users (there was no exercise so far if I remember correctly).

Your code so far

function myReplace(str, before, after) {
  return str.replace(new RegExp(before,"ig"), 
  (item) => {
    return (/[A-Z]/).test(item) ? after.slice(0, 1).toUpperCase() + after.slice(1) : after;

console.log(myReplace("A quick brown fox Jumped over the lazy dog", "jumped", "leaped"));

There are probably 20 ways of solving this challenge. If you are going for less complex, I would not use an explicit return and I would break the ternary down into multiple lines and indent the arguments to the replace method to make it more readable. Whether yours or my modification is less “complex” than the existing solutions is debatable.

function myReplace(str, before, after) {
  return str.replace(
    new RegExp(before,"ig"), 
    item => /[A-Z]/.test(item)
      ? after.slice(0, 1).toUpperCase() + after.slice(1)
      : after