Search and Replace in Javascript

The “Search and Replace” functionality is very common within word processing applications used for creating notes, documents and things of that nature. In this challenge, we implement this functionality in JavaScript in two distinct ways.

Curious already? Let’s see how!

You should already have your development environment setup for this course. Update your cloned repository by running the command git pull. Inside the Beginner folder, navigate to the searchReplace folder. Our work for this challenge will be done in here. Make sure to follow along in the index-START.js file.

The Challenge

Receiving a sentence, a word in the sentence and a replacement for that word as arguments, perform a search and replace on the sentence using the arguments provided and return the new sentence. E.g

searchReplace("He is Sleeping on the couch", "Sleeping", "sitting") 
// should return "He is Sitting on the couch"

Note: Make sure to match the casing(capitalization) of the string to be replaced as shown above.

To the code arena! πŸ‘¨πŸΎβ€πŸ’»

Code Implementation

We explore two ways to solve this challenge below. Both approaches make use of JavaScript’s .replace() method to search out and replace the specified word in the given statement.

The .replace() method is used to return a new string with some or all matches of a patternreplaced by a replacement. It accepts either a regular expression(regex) pattern or a string for replacement. It is used as shown below.

stringOfText.replace(pattern, replacement)

See how we utilize this below.

Using .replace()

function searchReplace(str, word, newWord){
    if ( word[0] === word[0].toUpperCase() ) {
        newWord = newWord[0].toUpperCase() + newWord.slice(1)
   }
   return str.replace(word, newWord)
}

Recall that a major objective in solving this challenge is to ensure that the replacing word matches the casing(capitalization) of the word to be replaced.

To achieve this, we use an if statement to check of the first letter of the word word[0] matches the uppercase equivalent word[0].toUpperCase() of the letter. If it does, we convert the first letter of the newWord(replacement) to uppercase and append the rest of the lowercase letters retrieved using the .slice() method.

.slice() when used on a string extracts a section of the string and returns it as a new string. It receives two arguments; the beginning index which is compulsory and the end index which is only optional.

Once we now have the newWord in same case as the word to be replaced, we call the .replace() method on the sentence passing in the word to be replaced word and the replacement newWord.

This returns a new sentence with the words swapped appropriately. Thus, we return it from our function as the final result.

If you’ve followed the course so far, then you must remember that we earlier learnt how regular expressions are used to specify patterns of character combinations in strings. Let’s see how we apply this knowledge in the second approach.

Using Regular Expressions

In this approach, we use a regular expression in searching through the string(sentence) for the pattern to be replaced.

function searchReplace(str, word, newWord) {
    let regex = new RegExp(word, "gi");
    if (/[A-Z]/.test(word[0])) {
        newWord = newWord.charAt(0).toUpperCase() + newWord.slice(1);
    }
    return str.replace(regex, newWord)
}

Notice how we use the RegExp() constructor function to create a regular expression out of the word to be replaced. This we store as regex.

Note: **g** and **i** as specified in the second argument are regular expression flags with the following meanings.g– Global search(look in the whole string and return all matches)
i– Case-insensitive search.

Next, using a regular expression /[A-Z]/ within the if statement, we test to see if the first letter in the word is capitalized. If it is, we adjust the replacement newWord accordingly.

At the end, knowing that the .replace() method may accept a regular expression specifying the pattern to be searched for, we call the .replace() method on the sentence passing in regex and the newWord.

This gives us a new string(sentence) with the appropriate replacement and so we return it as such.

Smooth! Right? Lest run some tests.

Testing

Testing Correctness with Jest
To test the solutions above, run the command below from your terminal.

npm run test searchReplace
  • Using .replace()
  • Using Regex

Kudos! We pass all tests.πŸ‘πŸΎ

Testing Performance with Jest
Here on JSPerf, we run a performance comparison of both solutions. The screenshot below reveals the result.

From the result, we notice that the faster solution is the first approach where we simply replace the word using **.replace()** ,while the regular expression method is approximately 72% slower.

Practical Application

“Search and Replace” finds it’s application mostly in word processing applications where a user may need to manipulate content by searching out and replacing every occurrence of a certain word. It is also a valid coding interview challenge.

Conclusion

We have now learnt to find and replace words within a certain piece of text.

We have also determined that the use of regex in solving this challenge only slows down the entire process. Hence, a more efficient way is to directly replace the desired word using the .replace() method.

Further Reading

To learn more about the techniques and concepts utilized above, you may use the following links:

See you in the next one! ✌🏿

Source: Scotch.io

phpInfo

avatar
  Subscribe  
Notify of