Javascript Coding Challenge for Beginners Q2


English (Auto-generated)

Hello everyone. Welcome to the second javascript coding challenge. Today, we will learn to use regular expressions to solve our problem. For those who don't know what regular expressions are. They're basically a pattern of characters that you can use to search or replace any text. Let's head into our first question for this question. We want to replace the string cat with another animal using regular expressions. So for example the string one cat. Two cats Will now become one dog to dog. Let's go ahead and pause the video come up with your own solution. And when you're ready we will solve the problem together. Now that you are ready. We will implement the function, replace drink. An easy way to replace a string in javascript is to simply use the built in dot replace function. This function takes in two parameters. The first parameter we will use regular expression which requires to us to put two backslash. The second parameter is the new value that we are returning. Which in our case we want to return it dog. So we will put dog inside. Now let's go back to our first parameter. We want to replace cat with dog. All you have to do with regular expression is put the word in between these two backslash. So let's try that. We're going to open the terminal and run it. Mhm. You'll see that in return one dog and two cats instead of one dog and two dogs, which is what we want. That is because in regular expression it only performs the first match unless you tell them otherwise. So in our case since we want a global match, all we have to do is put the letter G at the end of the last back slash for regular expressions. And then it will prefer a global search and a global replace. So let's try that again. As you can see now it is one dog and two dog. But some of you may be like what if I only want to replace certain letters? We can do that as well with regular expressions. So let's try another example. So example two, we will replace all the vowels in the strength. Thank you. We can use the same function. So I'm gonna copy and paste it and comment this out. I'm gonna save it. So since we want to replace all the values and the vowels not values vowels in the string, we're gonna replace cats. So when you want to replace any letters, you have to put two brackets, which means that anything in between these brackets will be searched for and replaced with. So in our case we want the vowels which is a I O U instead of dog. Maybe we want to put a start. Maybe you want to censor all the vowels. So let's try this again. In the terminal. As you can see all the vowels are now replaced with the start. Congratulations on completing the second challenge. When you're ready, we can go to the next challenge
92 Views 0 Likes 0 Comments

This challenge will teach you how to use regular expressions to solve the challenge.

Leave a comment (supports markdown format)