Week 7
Topic 7: String Data &
Regular Expressions
Lecture Overview
CIM 322 Saka D. 2
Manipulating Strings
• String: is any text contained within
double or single quotation marks or
literal values or assigned to a variable.
• Examples: ‘Hello’, “Hello”
• It must begin and end with same type
of quotation mark.
• In manipulating strings, you will often
find it necessary to parse the string.
CIM 322 Saka D. 3
• String parsing: refers to the act of
extracting characters or substrings from a
larger string.
• It also means extracting information about
literal strings and variables
• To parse the text strings in your scripts, you
need the String class.
• The String class contains all the necessary
methods and properties for manipulating
text strings.
CIM 322 Saka D. 4
Formatting Strings
Displaying Special Characters
• Special characters: characters not found on
the keyboard.
• To display special characters, use Unicode.
• Unicode: a standardized set of characters
from many of the world’s languages.
• Example: © for copy right symbol.
CIM 322 Saka D. 5
Changing Case
• There are 2 methods for changing case:
• toLowerCase() method: converts a text
string to lowercase.
• toUpperCase() method: converts a text
string to uppercase
• N/B: the methods do not change the
original string.
CIM 322 Saka D. 6
• Example:
var mail = “JOHN@[Link]
var email = [Link]();
[Link](email)// john@[Link]
CIM 322 Saka D. 7
• Example: App converts email to
lowercase and displays special character
CIM 322 Saka D. 8
Example: [Link]
<!DOCTYPE html>
<html>
<head><title>Changing Case</title></head>
<body>
<h2 align="center">Text Formatting</h2>
<form>
email Address:<input type="text" id="txtmail" size = "20" value="" />
<input type="button" id="butsubmit" value="Submit" onClick="stringFormat()" />
</form>
<p id="p1"></p> <p id="p2" align="center"></p>
<script>
function stringFormat(){
var mail = [Link]("txtmail").value;
var email = [Link]();
[Link]("p1").innerHTML = "Correct email format: " + email;
var copyRight = "Copyright © 2022";
[Link]("p2").innerHTML = copyRight;
}
</script>
</body>
</html>
CIM 322 Saka D. 9
Determining the Number of
Characters in a String
• Use the length property.
• The property returns the number of
characters in a string.
• Example:
var name = “John”;
var len = [Link];
CIM 322 Saka D. 10
• Example: App to validate character
length
CIM 322 Saka D. 11
• Example: [Link]
<h2 align="center">Create Account</h2>
<form>
User name:<input type="text" id="txtusername" size = "20" value="" />
<p id="p1" style = "color: red;"></p>
Password:<input type="password" id="txtpwd1" size = "20" value="" />
<p id="p2" style = "color: red;"></p>
<input type="button" id="butsubmit" value="Submit" onClick="validateDetails()" />
</form>
<script>
function validateDetails(){
var userName = [Link]("txtusername").value;
var password = [Link]("txtpwd").value;
if ([Link] < 4)
[Link]("p1").innerHTML = "User name must be at least 4 characters";
if ([Link] < 8)
[Link]("p2").innerHTML = "User name must be at least 8 characters";
}
</script>
CIM 322 Saka D. 12
Finding and Extracting
Characters and Substrings
• In string processing finding and
extracting characters and substrings
from a string is common place.
• For example, if your script receives an
email address, you may need to extract
the name portion of the email address
or domain name.
CIM 322 Saka D. 13
• There are two types of string search methods:
i. methods that return a numeric position in a
text string.
ii). methods that return a character or
substring.
N/B: For methods that return position, it is
important to remember that positioning starts
from index 0.
• Some common methods for doing this include:
CIM 322 Saka D. 14
1. The charAt(index) Method
• Returns the character at the position
specified by the index argument.
• Syntax:
var name = “John”;
var xter = [Link](3) // n
CIM 322 Saka D. 15
2. The indexOf(text, index) Method
• The method performs a case-sensitive
search and returns the position number of
the first character in the text argument;
• if the index argument is included, then the
indexOf() method starts searching at that
posi on within the string; returns −1 if the
character or string is not found.
CIM 322 Saka D. 16
3. lastIndexOf(text, index) Method
• The method performs a case-sensitive
search and returns the position number of
the last instance of the first character in the
text argument.
• if the index argument is included, then the
method starts searching at that position
within the string; returns −1 if the character
or string is not found.
CIM 322 Saka D. 17
• Example: extracting domain ID
var email = “john@[Link]”;
var startindex = [Link](“.”); // 10
var endindex = [Link](“.”); //13
var idstartposn = startindex + 1;
var idendposn = endindex – 1;
CIM 322 Saka D. 18
4. search(pattern) Method
• The method performs a case-sensitive search
and returns the position number in a string of
the first instance of the first character in the
pa ern argument; otherwise it returns −1 if
the character or string is not found.
• Example:
var email = "president@[Link]";
var atPosition = [Link]("@"); // returns 9
CIM 322 Saka D. 19
5. match(pattern) Method
• The method performs a case-sensitive
search and returns an array containing the
results that match the pattern argument
otherwise it returns value NULL if the text is
not found.
• Example:
var email = "president@[Link]";
var found = [Link]("house");
[Link](found); // prints “house”
CIM 322 Saka D. 20
6. slice(startindex, endindex) Method
• Extracts text from a string, starting with
the position number of the startindex
argument and ending with the
character immediately before the
position number of the endindex
argument.
• Note: The method allows negative
argument values.
CIM 322 Saka D. 21
• Example 1:
var email = "president@[Link]";
var domainID = [Link](-3);
[Link](doimainID) // domainID value is "gov"
• Example 2:
var email = "president@[Link]";
var domainBegin = [Link]("@") + 1;
var domainEnd = [Link](".");
var domain = [Link](domainBegin, domainEnd);
[Link](domain); // "whitehouse"
CIM 322 Saka D. 22
7. substr(start, length) Method
• Returns the substring from the start
position through the number of
characters specified by the length
argument.
• Example:
CIM 322 Saka D. 23
8. substring(start) method
• Returns the string from the start
position to the end of the string.
• Example:
var email = "president@[Link]";
var domainBegin = [Link]("@") + 1;
var domainID = [Link](domainBegin);
CIM 322 Saka D. 24
9. substring(start, end) method
• Returns the string from the start
position to, but not including the end
position.
• Example:
CIM 322 Saka D. 25
• Example: To use the search() and
lastIndexOf() methods to check whether
an email address contains an @ sign
and a period:
if ([Link]("@") === -1 ||
[Link](".") === -1) {
[Link] ("Please provide a valid email
address“);
}
CIM 322 Saka D. 26
Replacing Characters and
Substrings
• The replace() method replaces the first
matching pattern it finds in the string with
the text.
• Syntax:
[Link](pattern, text);
• Example:
var email = "president@[Link]";
var newEmail = [Link]("president",
"[Link]");
CIM 322 Saka D. 27
Combining Characters and
Substrings
• In addition to the concatenation
operator + and the compound
assignment operator (+=) , the String
class also includes the concat()
method.
• Syntax:
[Link](value1, value2, ...)
CIM 322 Saka D. 28
Comparing Strings
• Use the comparison operator (===).
• Example:
if (!(password1 === password2) )
[Link](“Passwords do not
match!”);
CIM 322 Saka D. 29
Using Regular Expressions
• Regular expressions: are patterns that
can be used to search pattern in a
string.
• Regular expressions are most commonly
used for validating submitted form data
e.g. ensure that a user enters a data in a
specific format such as a telephone
number in the format (###) ###-####.
CIM 322 Saka D. 30
Creating a Regular Expression
Object
Alternative 1: Using RegExp Constructor
var pattern = new RegExp("Babbage");
Alternative 2: Using Regular expression
literal
var pattern = /Babbage/;
• N/B: Regular expression patterns are
not enclosed in double-quotes (“”).
CIM 322 Saka D. 31
Searching for a Regular
Expression Pattern in a String
• The test method is used to search for a
pattern in a given string.
• Example:
var pattern = /Babbage/;
var inventor = "Charles Babbage";
var programmer = "Ada Lovelace";
[Link](inventor) ; // true
[Link](programmer) ; // false
CIM 322 Saka D. 32
How to Create a Case Insensitive
Regular Expression
• By default, a regular expression pattern is case
sensitive.
• You can change that by changing the ignoreCase
property of the RegExp object to true.
• Example:
var pattern = /lovelace/i;
[Link](programmer) ); // true
• The i modifier is called a flag.
• Flags are used to modify the behavior of a regular
expression.
CIM 322 Saka D. 33
Common Regular Expressions for
Testing Validity
1. A pattern for testing phone number
format - 9999-999-999:
/^\d{4}-\d{3}-\d{3}$/
2. A pattern for testing credit card number -
9999-9999-9999-9999:
/^\d{4}-\d{4}-\d{4}-\d{4}$/
3. A pattern for testing zip code format -
99999 or 99999-9999:
/^\d{5}(-\d{4})?$/
CIM 322 Saka D. 34
4. A pattern for testing email format -
username@[Link]:
/^[\w\.\-]+@[\w\.\-]+\.[a-zA-Z]+$/
5. A pattern for testing date format - yyyy
/mm/dd:
/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-
9]|3[01])$/;
CIM 322 Saka D. 35
• Examples
Testing a phone number for validity const
phone = “0722-555-664";
const phonePattern = /^\d{4}-\d{3}-
\d{3}$/;
if (  ) {
alert("Invalid phone number");
}
CIM 322 Saka D. 36
Example 2: Testing a date for a valid format,
but not for a valid month, day, and year
const startDate = "8/10/220"; // invalid date
const datePattern = /^[01]?\d\/[0-
3]\d\/\d{4}$/; // this pattern will match
dates like 19/21/2020 and 9/39/2021
if (  ) {
alert("Invalid start date");
}
CIM 322 Saka D. 37
• Example:
CIM 322 Saka D. 38
• On 2nd run: Some fields corrected
CIM 322 Saka D. 39
• Example: [Link]
<!DOCTYPE html>
<html>
<head><title>Regular Expressions</title></head>
<body>
<h2 align="center">Register Account</h2>
<form>
Full Name:<input type="text" id="name" size = "20" value="" /> <span id="name_error" style="color: red;"
> </span><br><br>
Password:<input type="password" id="pwd1" size = "20" value="" /> <span id="pwd1_error" style="color:
red;"> </span><br><br>
Confirm Password:<input type="password" id="pwd2" size = "20" value="" /> <span id="pwd2_error"
style="color: red;"> </span><br><br>
Email:<input type="text" id="email" size = "20" value="" /> <span id="email_error" style="color:
red;"> </span>
<p>Format: john@[Link]</p>
Phone Number:<input type="text" id="phone" size = "20" value="" /> <span id="phone_error"
style="color: red;"> </span>
<p>Format: 0XXX-XXX-XXX </p>
<input type="button" id="butsubmit" value="Register" onClick="validatePatterns()" />
<input type="reset" Value="Clear Form" />
</form>
<script>
CIM 322 Saka D. 40
function validatePatterns(){
const emailPattern = /^[\w\.\-]+@[\w\.\-]+\.[a-zA-Z]+$/
const phonePattern = /^\d{4}-\d{3}-\d{3}$/;
var userName = [Link]("name").value;
var password1 = [Link]("pwd1").value;
var password2 = [Link]("pwd2").value;
var email = [Link]("email").value;
var phone = [Link]("phone").value;
if ([Link] < 4)
[Link]("name_error").innerHTML = "User name must be at least 4 characters";
else
[Link]("name_error").innerHTML = "";
if ([Link] < 4)
[Link]("pwd1_error").innerHTML = "Password must be at least 4 characters";
else
[Link]("pwd1_error").innerHTML = "";
CIM 322 Saka D. 41
if ( password1 !== password2)
[Link]("pwd2_error").innerHTML = "Passwords do not match";
else
[Link]("pwd2_error").innerHTML = "";
if ([Link](email) )
[Link]("email_error").innerHTML = "";
else
[Link]("email_error").innerHTML = "Invalid email format";
if ([Link](phone) )
[Link]("phone_error").innerHTML = "";
else
[Link]("phone_error").innerHTML = "Invalid phone
number";
}
</script>
</body>
</html>
CIM 322 Saka D. 42