Simple solution for search and replace challenge

function myReplace(str, before, after) {
       if(before !== before.toLowerCase()){
            after = after.charAt(0).toUpperCase() + after.slice(1);
                str = str.replace(before,after);
       } else {
         str = str.replace(before,after);
  return str;

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

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard.


@Nuno-Filipe-Silva Another way to do it:

function myReplace(sentence, before, after) {

	if(before.charCodeAt(0) < 91) {
		let ch = after.charAt(0);
		after = after.replace(ch, ch.toUpperCase());
	} return sentence.replace(before, after);

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
1 Like

After this fun post and one-liner challenge, I thought it’d be fun to try the same with this one, improving on what I had originally used as my solution:

function myReplace(str, before, after) {
  return str.replace(before,
    before.charAt(0) === before.charAt(0).toUpperCase()
      ? after.charAt(0).toUpperCase() + after.slice(1)
      : after

The trouble with these one-liners though is that while fun, they’re often not as readable. I like Crockford’s suggestion to split the ternary operator into multiple lines.

Also, this also isn’t very robust, and only considers the first character for preserving case (as the challenge requires). Working tech-support for over two years has pushed me to value considering the edge-case. Might be fun to try to see how this could be pushed to preserve case for the entirety of the string.

Hey, thanks for the compliment, and same goes right back at you. You’re absolutely right, no need for the else. Many thanks, and keep up the good work

hi. thanks for the edit and advice.

hi. nice code, i’ll look into it, it’s a bit out of my league, using the let and the 91. but this is the purpose of the forum, learn and evolve. Many thanks

hi. couldn’t agree more, readability is a big help in finding bugs

As far as concerned to let (it is same as var, but it restricts the access only for the current block), it’s included in ES6 standards. And 91 is a ASCII code, which i used in the logic, as we know, all small and capital letters has different ASCII codes, so: 65-90 represents A-Z and 97-122 represents a-z. So if we look at this condition: if(before.charCodeAt(0) < 91) { ... } that ensures if the first letter of before is in capital letter then make the first letter of after in capital letter as well.