Use case of RegEx in JavaScript
Published on: 16th Mar 2023
Updated on: 18th Mar 2023
Overview
String operation is very common in any program especially those requires in processing user input. For example, in Membership Management System and the back end system that is processing the JSON string from other system or user.
Use case
-
Ensure that the first character is in upper case,
let user_input = 'abc'; if (!/^[A-Z]/.test(user_input)) { console.log('The user input is not start with upper case'); }
-
Using RegEx like SQL IN operator,
let user_input = 'BANANA'; if (/APPLE|BANANA/.test(user_input)) { console.log('The user input has either apple or banana'); }
In case the user might key in the value in lower or mixed case, add
i
flag (case insensitive) after the second '/',let user_input = 'Banana'; if (/APPLE|BANANA/i.test(user_input)) { console.log('The user input has either apple or banana'); }
This useful technique is good for validating the city name in the address fields.
Unsuitable use case: for example, the user input is limited to either 1, 3 or 5. By using following RegEx, it returns true which is an unexpected result.
console.log(/1|3|5/i.test('13')); // output: true
The correct way to get the expected result is to use
indexOf()
function provided by an array,console.log(['1', '3', '5'].indexOf('13') >= 0); // output: false
-
Using RegEx like SQL LIKE operator,
console.log(/m.*ing/.test('good morning')); // output: true console.log(/m.*ing/.test('good mornin')); // output: false console.log(/m.*ing/.test('good afternoon')); // output: false
-
Extract a text block from a very long string,
let some_string = '{"name":"mike"}{"name":"john"}'; const RG = /{.*?}/g; // find the first block let match = RG.exec(some_string); console.log(match[1]); // output: {"name":"mike"} // search for next block match = RG.exec(some_string); console.log(match[1]); // output: {"name":"john"}
Where
g
indicates global (i.e., continue look for next matches from the last position)..*
means any character.?
means the searching process will stop once it found the first '}' symbol. Without this, the result might return the entire string.
In case you want to use RG again for other value in
some_string
, you must reset the last search position.RG.lastIndex = -1;
-
Extract multiple text blocks with capturing group (the
(
and)
that wraps the\d
) from the user input,let user_input = '1999-02-03'; let match = /(\d{4})-(\d{2})-(\d{2})/.exec(user_input); // output: match[1]=1999 // output: match[2]=02 // output: match[3]=03
where
\d
indicates that we are looking for "a single digit" or "numeric".{4}
means 4 consecutive digits.- The
(
and)
is the capturing group and the matches can be accessed withmatch[1]
,match[2]
andmatch[3]
in this example.
-
Replaces all occurrences of carrige and line feed characters in the given text,
let user_input = 'Helo Mike,\r\nWelcome to our blog\r\nSome more information here..'; let user_input2 = user_input.replace(/\r\n/g, '<br/>');
Conclusion
Using RegEx to validate and process user input makes the program simpler and easier to maintain.
Related posts
- For a more complex usage of RegEx, please refers to one of the earlier post: Parsing CREATE TABLE statement with Regex in Node.js
Jump to #JAVASCRIPT blog
Jump to #NODEJS blog
Author
Lau Hon Wan, software developer.