DEV Community

Themba🇿🇦
Themba🇿🇦

Posted on

How to use regex in javascript:

Hey, for today’s blog we going to create a function which takes away spaces and special characters from an input and inserts an underscore using regular expressions or regex.
The reason you would need this piece of code is, special characters can cause alot of problems in your database and system if not handled properly so you would need a way to get rid of them if a user had to insert them.

So what is a regular expression.
A regular expression, commonly referred to as regex or regexp, is a sequence of characters that define a search pattern. It is mainly used for text-based searching and string manipulation.

So for our program we going to create a simple input with a button which will display the word inside the input when clicked, but if the word inside the input has spaces or special characters it will replace it with an underscore.

<input type="text">
<button onclick="displayWord()">Display</button>
<h1 id="word"></h1>
Enter fullscreen mode Exit fullscreen mode
function displayWord() {
         let word = document.querySelector('input').value // Grab the value inside the input
         .trim() // remove all the white space on the left and right
         .replace(/[\s\W]+/ig, "_"); // replace all spaces in between words and all characters with underscore

           document.getElementById("word").innerHTML = word;
        }
Enter fullscreen mode Exit fullscreen mode

Inside our replace function I added in regex, the “\s” is looking for all the spaces and the \W is looking for all the non-word characters or special characters which are for e.g: !, @, #, $, %.... The “+” just means that the regex should look for one or more occurrences of the whatever we looking for. The “i” means that the regex should be case-insensitive meaning it should treat “HELLO” the same as “hello”. The “g” means the regular expression should perform a global match meaning if a sentence contains multiple instances of the same word it should find all of them and not just stop on the first match.

Top comments (0)