DEV Community

Viren B
Viren B

Posted on • Originally published at virenb.cc

Solving "Search and Replace" / freeCodeCamp Algorithm Challenges

Search and Replace

Let's solve freeCodeCamp's intermediate algorithm scripting challenge, 'Search and Replace'.

Starter Code

function myReplace(str, before, after) {
  return str;
}

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

Instructions

Perform a search and replace on the sentence using the arguments provided and return the new sentence.

First argument is the sentence to perform the search and replace on.

Second argument is the word that you will be replacing (before).

Third argument is what you will be replacing the second argument with (after).

Note
Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog"

Test Cases

myReplace("Let us go to the store", "store", "mall") should return "Let us go to the mall".
myReplace("He is Sleeping on the couch", "Sleeping", "sitting") should return "He is Sitting on the couch".
myReplace("This has a spellngi error", "spellngi", "spelling") should return "This has a spelling error".
myReplace("His name is Tom", "Tom", "john") should return "His name is John".
myReplace("Let us get back to more Coding", "Coding", "algorithms") should return "Let us get back to more Algorithms".

Our Approach

After reading the starter code, instructions, and test cases, this is what I summarized about this challenge -

  • We have three inputs, all which are strings. str is a sentence (with some white spacing), before and after are one word strings.
  • We must return a string (a sentence based on the test cases).
  • We essentially need to replace a word in str with the 3rd argument, after. We will have to factor in if the word is capitalized or not before replacing it.

Having worked with regular expressions in the last two challenges, using it again might come in handy. I'm thinking we will use it to compare before and after, if before is capitalized, we can change after.

My first action would be to split(' ') str from a sentence into an array of words so it will be easier to compare/replace.

str = "A quick brown fox jumped over the lazy dog";
str.split(' ');
// Array(9) [ "A", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog" ]

Next, we can check before to see if it is capitalized. This can be accomplished with an if statement. Looking for a capitalized letter in RegEx is more straight foward than our past exercises.

/^[A-Z]/ - A-Z character range, case sensitive. Will check for the first character in the word. Running test() will return a true or false value.

/^[A-Z]/.test('Hello')
// true

/^[A-Z]/.test('hELLO')
// false

So, our if statement will run the above RegEx test on before. If it is true, that means it begins with a capital letter and we will then change after to also begin with a capital letter.

// if true, we're changing after variable, capitalizing the first character (charAt(0)) and adding rest of the characters to it
// if test is false, no else statement needed, so after does not change

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

Since our str is split up into an array, we're going to call splice() on it to replace the words.

Array.splice() on MDN

Just a quick little example on how it works -

const arr = ['chocolate', 'milk', 'is', 'great'];
// array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
// start is index you want to alter, deleteCount is option, items are optional too
// Let's change how we feel about chocolate milk
arr.splice(3, 1, 'AWESOME')
// Result:  [ "chocolate", "milk", "is", "AWESOME" ]

So since we want to replace before word in strSplit, we can look up it's index using indexOf.

Array.indexOf()

strSplit.splice(strSplit.indexOf(before), 1, after)

We're locating the index where before is, inserting one item in that index, the item being after.

The last steps are to join(' ') splitStr back into a string from an array and return the value.

Our Solution

function myReplace(str, before, after) {
  const strSplit = str.split(' ');

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

  strSplit.splice(strSplit.indexOf(before), 1, after);
  return strSplit.join(' ');
}

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

Links & Resources

'Search and Replace' Challenge on fCC

freeCodeCamp

Donate to FCC!

Solution on my GitHub

Thank you for reading!

Latest comments (0)