Regular expressions in programming: practical examples for JavaScript
Among many other things, learning to program involves memorizing expressions and steps that allow you to carry out simple and practical actions. A good comparison would be the typical keyboard shortcuts that enable you to use a simple combination of keys to go to the explorer, close the browser, search for a program and so on. In some programming languages, regular expressions serve to detect patterns in different text strings. With a single step, these regular expressions make programmers’ work much easier.
A very simple example is using a regular expression to verify whether the information on a form filled out by users is correct or not. A short form may be used to collect the customers’ first and last names and contact telephone number, but some customers may fail to correctly complete this last field. The fastest way to check this is through a regular expression. Developers who regularly use Perl for their projects are very familiar with these tools and can do this thanks to simple shortcuts.
But Perl programmers are not the only developers who can exploit the benefits of regular expressions. JavaScript professionals can also use them, and especially to make specific verifications in different text strings based on a pattern that can be summarized in an open expression. Analytical tools such as Google Analytics can also be used.
This is how regular expressions are used in JavaScript
Regular expressions use characters and metacharacters to openly define specific patterns in text strings. By combining these characters with others in a particular way, you can search for items or specific elements to be extracted from these strings in order to search or manipulate the text (identifiers, emails…). In the case of JavaScript, there are two types of regular expressions:
● Regular expressions via a literal string to find a pattern: these use the object constructor RegExp. A RegExp literal is created using this expression: var re = /regular expression/;. The regular expression pattern appears between the opening and closing backslashes, a structure that tends to be habitual and obligatory.
● Regular expressions applied to several strings: expReg.test(string). If there’s a match between the expression and a possible pattern, it returns true; and false if not.
Some special elements for making regular expressions in JavaScript:
● ^: the element must be matched from the start of the string.
● [A-Z]: any character between capital A and capital Z.
● {1,2}: one or two characters.
● \s: a blank space.
● \d: one digit.
● {4}: four digits.
● \s: a blank space.
● ([B-D]|[F-H]|[J-N]|[P-T]|[V-Z]): any character between capital B and capital Z, except vowels.
● {3}: three characters.
● $: the element must be matched to the end of the string.
Specific cases of use of regular expressions
Regular expressions are often used to detect whether there is a specific sequence of letters, words or numbers in a particular string. This can be done by using a simple regular expression:
var reg = /javascript/;
“This is javaScript” language.match(reg);
// returns an array of an element [“javascript”], as there is an element with that specific sequence of letters within the string. If the words “javaScript” do not appear in the string, it will return a null element.
Sometimes the element if is used to find true or false matches from a combination of characters and words (expressions) in a complete string:
if (“This is javaScript” language”.match(/javascript/) {
// This will return true because the javaScript element appears in the string.
}
if (“This is javaScript” language”.match(/javascript/) {
// This will return false because the javaScript element doesn’t appear in the string.
}
Using the element linked to the search for digits, regular expressions can check whether a string has a specific digit, and can even be programmed to detect combinations and repetitions of series of digits within one or several text strings:
– Search for a specific digit in a text chain: in this particular case, the programmer searches to see whether the text string contains the number 2. As it does, the regular expression logically returns a [“2”].
“This number is a 2”.match(/\d/); // Returns a [“2”]
– Regular expressions are also able to detect the repetition of one or several digits within a text string or a specific sequence of numbers within the same text string. The only thing you need to do is to repeat the elements \d within the expression, which must be accompanied by the symbol / at the beginning and end:
“This number is 242”.match(/\d\d\d/); // Returns [“242”] because there is an expression containing 3 consecutive digits within this string.
– To search for digits in different text strings:
/\d{3}/ Search 3 digits in the string
/\d{1,5}/ Search for between 1 and 5 digits in the string.
/\d{2,}/ Search for 2 or more digits in the string.
Here are just a few specific examples with this last regular expression: in the first example, the expression allows you to search for a maximum of two digits in a particular text string (in this case, “1234”), so it returns the element [“12”]; in the second case, the search is for between one and three digits, so it returns [“123”]; and in the third case, the expression searches for between three and ten digits, so it returns four, the full text string: [“1234”].
“1234”.match(/\d{2}/);
[“12”]
“1234”.match(/\d{1,3}/);
[“123”]
“1234”.match(/\d{3,10}/)
[“1234”]
API WorldRegular expressions in programming: practical examples for JavaScript
Banco Bilbao Vizcaya Argentaria, S.A. owner of this portal uses cookies and/or similar technologies of its own and third parties for the purposes of personalization, analytics, behavioral advertising or advertising related to your preferences based on a profile prepared from your browsing habits (e.g. pages visited). If you wish to obtain more detailed information, consult our Cookies Policy.
Cookie settings panel
These are the advanced settings for first-party and third-party cookies. Here you can change the parameters that will affect your browsing experience on this website.
Technical Cookies (required)
These cookies are used to give you secure access to areas with personal information and to identify you when you log in.
Name
Owner
Duration
Description
gobp.lang
BBVA
1 month
Language preference
aceptarCookies
BBVA
1 year
Configuration Accepted Cookies
_abck
BBVA
1 year
Helps protect against malicious website attacks
bm_sz
BBVA
4 hours
Helps protect against malicious website attacks
ADRUM_BTs
Salesforce Marketing Cloud
Session
Required for monitoring of the service, inherent to SFMC
ADRUM_BT1
Salesforce Marketing Cloud
Session
Required for monitoring of the service, inherent to SFMC
ADRUM_BTa
Salesforce Marketing Cloud
Session
Required for monitoring of the service, inherent to SFMC
ADRUM_BT
Salesforce Marketing Cloud
Session
Required for monitoring of the service, inherent to SFMC
xt_0d95e
Salesforce Marketing Cloud
Session
Remember user preferences (if any)
__s9744cdb192d044faa1bf201d29fafd1e
Salesforce Marketing Cloud
Session
Remember user preferences (if any)
wpml_browser_redirect_test
WPML
Session
Text translation in the portal
wp-wpml_current_language
WPML
24 hours
Text translation in the portal
Analytics Cookies
They are used to track the activity or number of visits anonymously. Thanks to them we can constantly improve your browsing experience
Your browsing experience is constantly improving.
With your selection, we cannot offer you a continuously improved browsing experience.
Name
Owner
Duration
Description
AMCV_***
Adobe Analytics
Session
Unique Visitor IDs used in Cloud Marketing solutions
AMCVS_***
Adobe Analytics
2 years
Unique Visitor IDs used in Cloud Marketing solutions
demdex (safari)
Adobe Analytics
180 days
Create and store unique and persistent identifiers
sessionID
Adobe Analytics
Session
Launch's internal cookie used to identify the user
gpv_URL
Adobe Analytics
Session
Adobe Analytics plugin: getPreviousValue Capture the value of a certain variable in the following page view, in this case the prop1
gpv_level1
Adobe Analytics
Session
Cookie used to store the DataLayer levl1 of the previous page.
gpv_pageIntent
Adobe Analytics
Session
Cookie used to store the pageIntent of the previous page.
gpv_pageName
Adobe Analytics
Session
Cookie used to store the pagename of the previous page.
aocs
Adobe Analytics
Session
Cookie that stores the first values collected at the beginning of a process.
TTC
Adobe Analytics
Session
Cookie used to store the time between the App Page Visit event and the App Completed event.
TTCL
Adobe Analytics
Session
Cookie used to store the time between the LogIn event and App Completed.
s_cc
Adobe Analytics
Session
Determine if cookies are active
s_hc
Adobe Analytics
Session
Cookie used by Adobe for analytical purposes
s_ht
Adobe Analytics
Session
Cookie used by Adobe for analytical purposes
s_nr
Adobe Analytics
2 years
Determine the number of user visits
s_ppv
Adobe Analytics
Permanent
Adobe Analytics plugin: getPercentPageViewed Determine what percentage of the page a user views
s_sq
Adobe Analytics
Session
ClickMap/ActivityMap features
s_tp
Adobe Analytics
Session
Cookie used by Adobe for analytical purposes
s_visit
Adobe Analytics
2 years
Cookie used by Adobe to know when a session has been started.
Advertising Cookies
They allow the advertising shown to you to be customized and relevant to you. Thanks to these cookies, you will not see ads that you are not interested in.
The advertising is customized to you and your preferences.
Your choice means you will not see customized ads, only generic ones.
Name
Owner
Duration
Description
OT2
VersaTag
90 days
VersaTag Cookie used to store a user id and the number of user visits.
u2
VersaTag
90 days
VersaTag Cookie where the user ID is stored
TargetingInfo 2
MediaMind
1 year
Cookie that serves to assign a unique random number that generates MediaMind.
Customization Cookies
These cookies are related to general features such as the browser you use.
Your experience and content have been customized.
With your selection, we cannot offer you a continuously improved browsing experience.
Name
Owner
Duration
Description
mbox
Adobe Target
9 days
Cookie used by Adobe Target to test user experience customization.
Looks like you’re browsing from MexicoSpainArgentinaPeruColombiaBelgiumChileUSAFranceHong KongItalyPortugalUnited KingdomTurkeyUruguayVenezuelaAlemania, so let’s show you the custom content for your
location. Change
Select a country
In order to access the private area and corresponding sandbox, select the country of the APIs you want to use.