FCC Bonfire Series 122: Search and Replace

This next bonfire, Search and Replace, will have us write a function that takes in three (3) arguments.

  • A sentence.
  • A word present inside the sentence (this is what we are going to be replacing).
  • Another word (we will replace the second argument with this word in the original string).

For this task, we are going to be using regular expressions and the String.prototype.replace() method. The replace method takes in two arguments, a pattern -which can be a regular expression or not- to match the text to be replaced and the string (or string constructing function) to replace it with. Here’s an example:

var myString = 'This is a dog.';
console.log(myStirng.replace('dog', 'cat')); //-> 'This is a cat.'

In our case, we’ll make use of regular expressions to achieve a similar effect. The initial function barebone may look like this:

function replace(str, before, after) {
	var re = new RegExp(before, 'g');    //-> We use the RegExp constructor method to create a regular expression out of a variable.
	return str.replace(re, after);

This should work pretty well, but has a problem. We are asked to mantain the original capitalization of the replaced word, look at this case:

var myString = 'My name is John.';
var newString = replace(myString, 'John', 'joe');
console.log(newString);  //-> 'My name is joe.'

We must return the sentence with the word capitalized properly. How about we use another regular expression to detect capitalization -using the test method-, and act accordingly? Remember, if you are not too familiar with regular expressions, here’s a great source.

function replace(str, before, after) {
  var re = new RegExp(before, 'g');
  var upper = /^[A-Z]/;
  if (upper.test(before)) {
    after = after.substr(0, 1).toUpperCase() + after.substr(1);
  return str.replace(re, after);

In this new function, we check if the work to be replaced is capitalized, and if so, we transform our after variable, so that the first letter is also capitalized.

We now have a working function! Stay sharp and stay tuned, we are getting to the harder parts!