freeCodeCamp Challenge Guide: Search and Replace

this should be an interesting solution :slight_smile:

function myReplace(str, before, after) {
return before[0] === before[0].toUpperCase() ?
str.replace(before, after = after.replace(after[0], after[0].toUpperCase())) : str.replace(before,after);
}

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

1 Like

Here is my not very elegant solution:

function myReplace(str, before, after) {
	
	var stringArr = str.split(' ');
	var newStr = '';
	var regex = /([a-z])([a-zA-Z]*)/g;
	var replacer = function (match, p1, p2, p3, offset, string) {
	    return p1.toUpperCase() + p2;
	};
		
	stringArr.forEach(function(element, index){
		if (element.indexOf(before) === 0) {
			if(/[A-Z]/.test(stringArr[index][0])) {
				stringArr[index] = after.replace(regex, replacer);
			} else {
				stringArr[index] = after;
			}
		}
		newStr = stringArr.join(' ');
	});
	return newStr;
}
1 Like

if you do not want to use replace function:

function myReplace(str, before, after) {
  var i = 0;
  after = after.toLowerCase();
  before = before.split("");
  after = after.split("");
  for(i = 0; i< before.length; i++){
    if(before[i].charCodeAt(0) >= 65 && before[i].charCodeAt(0 ) <= 90) {
      after[i] = after[i].toUpperCase();
    } 
  }
  after = after.join("");
  before = before.join("");
  str = str.split(" ");
  for(i = 0; i< str.length; i++){
    if(str[i] == before) {
      str[i] = after;
    }
  }
  str = str.join(" ");
  return str;
}

1 Like

Use regex to check if first character of ‘before’ is capital and if so change. Then replace:

function myReplace(str, before, after) {

  if (/[A-Z]/.test(before[0])) {
    after = after.charAt(0).toUpperCase() + after.slice(1);
  }

  var newStr = str.replace(before, after);  

  return newStr;
}

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

After having to look up solutions for a few past exercises, it felt really good to reach the solution on my own for this exercise :triumph:

function myReplace(str, before, after) {
  var character = before.charAt(0);
  if (character == character.toUpperCase()) {
   after = after[0].toUpperCase() + after.slice(1);
  }
  if (character == character.toLowerCase()){
   after = after[0].toLowerCase() + after.slice(1);
  }
  var newStr = str.replace(before, after);
  return newStr;
}

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

My Solution for this exercise:

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

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

these are finally becoming fun

5 Likes

Hello fellow campers!

Here’s my twist for this challenge:

function myReplace(str, before, after) {
  
  var titleCased = "",
      morph = "";
     
  titleCased = after.replace(after[0], after[0].toUpperCase());
         
  if(/[a-z]/.test(after[0]) === true && /[a-z]/.test(before[0]) === true){        
    morph = str.replace(before, after);        
  } else if(/[A-Z]/.test(after[0]) === false) {        
    morph = str.replace(before, titleCased);        
  }      
  return morph;      
}

myReplace("Let us get back to more Coding", "Coding", "algorithms");

How can you not love JS? :slight_smile: So many solutions !

1 Like

function myReplace(str, before, after) {
var newstr;
var charactere = before.substring(0,1);
if(charactere.charCodeAt(0)>=65 && charactere.charCodeAt(0)<=90){
newstr = after.split(’’);
newstr[0] = after.substring(0,1).toUpperCase();
return str.replace(before, newstr.join(’’));
} else {
return str.replace(before, after);
}
}

myReplace(“This has a spellngi error”, “spellngi”, “spelling”);

1 Like

Simple solution

function myReplace(str, before, after) {
  
  //Capitalize After if before is cap
  if (before[0] === before[0].toUpperCase()){
    after = after.charAt(0).toUpperCase() + after.slice(1);
  }
  
  //Regex to grab the value in the word
  var re = new RegExp(before,"g");
  str=str.replace(re, after);
  
  return str;
}

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

This is really clever!

1 Like

I am just learning so I compared the charCodeAt() results

function myReplace(str, before, after) {


 if(before.charCodeAt(0) < 93 && after.charCodeAt(0) > 93){

  //replacing lower case with upper case
  // i should do the reverse but there's none in the tests

  var x = after.charCodeAt(0) - 32;
  var y = String.fromCharCode(x);
  after = after.replace(/[a-z]/,y);

  }



var words = str.split(" ");

  for (i=0; i<words.length; i++){

    if (words[i] == before){
    words.splice(i,1);
  
    words.splice(i, 0, after);
    words = words.join();
    words = words.replace(/,/g, " ");
  
  }

 }

return words;
}

myReplace("Let us get back to more Coding", "Coding", "algorithms");
1 Like

what if before string’s first letter is in lowercase and after’s first letter is in uppercase

3 Likes
function myReplace(str, before, after) {
  // change string into array and add variable that store index of "before" argument
  let arr = str.split(' '),
      delIndex;
  // loop array, search delIndex and make condition if first letter is upper case
  arr.forEach((item,index) => {
   if(item === before) {
      delindex = index;
      if (before[0] === before[0].toUpperCase()) {
        after = after.replace(after[0], after[0].toUpperCase());
     }
    }
  });
  //raplace before => after
  arr.splice(delindex, 1, after);
  
  return arr.join(' ');
}

myReplace("This has a spellngi error", "spellngi", "spelling");

Maybe this is not the most efficient code, but it works.

2 Likes