Solving "Search and Replace" / freeCodeCamp Algorithm Challenges
Tags: freecodecamp, algorithms, challenge, javascript
Published: 2020-07-17 16:52:41

---
title: Solving "Search and Replace" / freeCodeCamp Algorithm Challenges
published: true
description: My guide, notes, and solution to freeCodeCamp's intermediate algorithm challenge, "Search and Replace" 
tags: #freeCodeCamp, #algorithms, #challenge, #javascript
canonical_url: https://virenb.cc/fcc-023-search-and-replace
series: Solving freeCodeCamp's Algorithm Challenges
---

![Search and Replace](//images.ctfassets.net/yzwpq1epaq68/1wkzU9qdgVoOKhDrIiRBi6/78afa7e2fc12ea041d4330868b3719e4/ss-023.png)

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



### Starter Code

```javascript
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.

```javascript
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.

```javascript
/^[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.



```javascript
// 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice "MDN Array.splice()")



Just a quick little example on how it works -

```javascript
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()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf "MDN 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

```javascript
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](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace "Intermediate Algorithm Scripting: Search and Replace on fCC Website")

[freeCodeCamp](https://www.freecodecamp.org/, "freeCodeCamp")

[Donate to FCC!](https://www.freecodecamp.org/donate "fCC Donation Page")

[Solution on my GitHub](https://github.com/virenb/fcc-algorithms/blob/master/023---search-and-replace.js "GitHub Solution")



Thank you for reading!