Retaining Regex
14th Aug 2022
My unexpected strategy
Practice, practice, practice
Recently, a fellow developer challenged me on codewars. I’ve spent many hours there solving code kata and he recommended I get on and do some more algorithm challenges.
Getting back to the practice of spending time doing random algorithm challenges wasn’t the first choice on my list but, I went ahead and jumped back in.
Practice builds confidence
After completing a few Kata, I really got back into the swing of things. For example, I felt very comfortable using array methods like map
due to my React experience… Then, I started using the MDN to look up other methods that I wasn’t using regularly. Soon, I was thinking about possible methods to solve certain problems and then specifically looking up the docs on those methods to see whether they were applicable.
Regex kept popping up
As I went through different challenges, I encountered some where regular expressions would be beneficial to solving them. Up until now, my strategy with regex was “look it up when needed”. Well, I’m not completely against that idea but, I felt that having a bit of retained foundational knowledge is a good goal to have.
Here were some important bits I saw multiple times:
const regex = /abc/
- a regular expression literal; a pattern enclosed between slashes
const regex = /abc/i
- the i
flag indicates a case-insensitive search
const regex = /abc/g
- the g
flag indicates that the regular expression should be tested against all possible matches in a string
const regex = new RegExp('foo', 'g');
const str = 'fooexamplefoo';
const str1 = str.replace(regex, '');
console.log(str1); // Output: example
const regex1 = new RegExp('foo');
const str2 = str.replace(regex1, '');
console.log(str2); // Output: examplefoo
Then, as if hit by a ton of bricks, retention happened
I started working on today’s Kata and as I was working through a problem where we were asked to break camel case words into two separate strings, I saw the opportunity to shine.
I decided to write the regex literal without trying to look it up first and when I ran my code, it worked first try!
function solution(string) {
const regex = /[A-Z]/g
return string
.split('')
.map((letter) => (letter.match(regex) ? ` ${letter}` : letter))
.join('')
}
The problem itself wasn’t too hard but, I was proud that I wrote the regex constant from memory.
A new routine
I’ve definitely experienced the value of adding Kata to my routine. I appreciate the fact that I also take other developers’ (especially those who double as a friend) advice to heart.