Regex only letters
In this tutorial let us decipher concisely about the regular expression concepts and a pattern which can only match the letters in a string.
What is a regular expression ?
A Regular expression is a sequence of characters that specifies a search pattern. In short as regex or regexp. These patterns are used to search the character combinations in strings.
Create a regular expression
Using a regular expression literal
var pattern = /ab*/;
Here, ab* is a pattern which is enclosed between slashes.
Using a constructor
var pattern = new Regex('ab*');
A regular expression constructor is used when the pattern is dynamic and is read as a user input.
How do we write Regular Expressions
Simple patterns are simple and can be used to find the direct match. For example /bat/ is a pattern which searches if "bat" is present in the string. This represents only a single pattern "bat"
Special characters a pattern which can search more than just a direct match encompasses different characters to extend its capability.
For example /ab/ can search a string for a, ab, abb, abbb, abbbb......, etc adding just a has extended its capacity.
These special characters fall into different categories listed as follows:
- Assertions which include boundaries.
- Character classes to distinguish different types of characters like letters, digits.
- Groups and Ranges refers to the groups and ranges of expression characters.
- Quantifiers refers to the number of characters or digits to match.
- Unicode property escapes to distinguish based on unicode properties.
Now, after understanding about the regular expressions. Let us now write a code that can search for only letters. Letters can be either lower case or upper case.
var str="Kodlogs"; => represents a pattern that searches for all the letters in a string.
=> There is an alternate way using the ignore case flag i.
var pattern = /[a-z]/gi => is equivalent to the pattern discussed formerly. This pattern also searches for the all the upper case and lower case letters. Using the ignore case flag to explicitly ignore the case.
The method match() will return an array of all matches found. Thus the output of this code is as follows:
'K', 'o', 'd',
'l', 'o', 'g',