Applications

Using Regex

🙋 Need help? Ask an expert now!

In JavaScript, regular expressions are used mostly when you need a search and replace function for long lines of text. Regular expression can be used to save time and to search for specific strings and characters without complicating you code with a bunch of functions and string methods. As mentioned previously, regular expression can also be used to validate user input and make sure the user inputted the information correctly.

The sample code above removes all white spaces and new lines using regex and replaces them with a single space. As you can see the original string within text is extremely messy, with multiple irregular spaces and unnecessary new lines. However, after using the replace() function (part of the String Object), the string is completely different and looks like a proper sentence with one space between each word. Without using regular expressions, trying to accomplish a task like this requires for loops and multiple lines of code.

Edit Me on GitHub!