Highlander

search and replace

Using Regular Expressions to Alter Strings

This was super fun! 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 that the case of the original word should be preserved when replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog".

There is some confusion on my part on the difference between certain methods of arrays and strings, specifically slice()and splice. These two functions, although they have similar names, are doing two completely different things.

Array’s slice accepts two arguments, start and end. It will return a new array containing the elements from the given start index up the one right before the specified end index.

Although splice also takes, at minimum,two arguments, the meaning is very different.On top of that, splice also mutates the array that calls it as the name implies.

There is also a string.slicemethod that extracts a section of a string and returns a new string. Changes to the text in one string do not affect the other string. I chose to convert the string (string.protoype.split()) to access the index where the second argument occurs (str.indexOf).

Using array.prototype.splice() we get a new array with var before replaced by var after

Finally, the return value is the new string with var after

This works, but what I failed to do was convert the second argument to uppercase. As I suspected, this would be the problem. First, test if the first argument is capitalized by checking against a RegEx. If it is capitalized, the third argument to match. to uppecase only returns the first char when using [] notation to access the index, so we must use the substring() method to add the capitalized letter to the remaining string

(I'm not as experienced with RegEx, so further study is on the agenda.) Put it all together, and voila! we have the correct solution:

Although there are many ways to skin a cat, this is the best I could do. If I was more familiar with regular expressions, there are more eloquent ways to have the same functionality. What has held me back in the past is trying to find that eloquence before I solve the problem, but I recently read something profound that changed this for me: “Everyone has a million bad words in them. Only once they’ve written those million words can they start writing well. So get writing!” This is applied to writing, but the same can be applied to code. So to me, the only way to get better is to keep doing, and worry about refinement another day.