0% found this document useful (0 votes)
4 views

CIT 415 Topic 7 String Data and Regular Expressions (1)

This document covers string data manipulation and regular expressions in programming. It explains string parsing, formatting, and methods for finding, extracting, replacing, and combining strings, as well as creating and using regular expressions for data validation. Examples are provided to illustrate the concepts, including email formatting and validation patterns.

Uploaded by

theeeclipse17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

CIT 415 Topic 7 String Data and Regular Expressions (1)

This document covers string data manipulation and regular expressions in programming. It explains string parsing, formatting, and methods for finding, extracting, replacing, and combining strings, as well as creating and using regular expressions for data validation. Examples are provided to illustrate the concepts, including email formatting and validation patterns.

Uploaded by

theeeclipse17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

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 = “[email protected]
var email = mail.toLowerCase();
document.write(email)// [email protected]

CIM 322 Saka D. 7


• Example: App converts email to
lowercase and displays special character

CIM 322 Saka D. 8


Example: ex7-1FormatText.html
<!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 = document.getElementById("txtmail").value;
var email = mail.toLowerCase();
document.getElementById("p1").innerHTML = "Correct email format: " + email;
var copyRight = "Copyright &#169 2022";
document.getElementById("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 = name.length;

CIM 322 Saka D. 10


• Example: App to validate character
length

CIM 322 Saka D. 11


• Example: ex7-2Length.html
<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 = document.getElementById("txtusername").value;
var password = document.getElementById("txtpwd").value;
if (userName.length < 4)
document.getElementById("p1").innerHTML = "User name must be at least 4 characters";
if (password.length < 8)
document.getElementById("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 = name.charAt(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 = “[email protected]”;
var startindex = email.indexOf(“.”); // 10
var endindex = email.lastIndexOf(“.”); //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 = "[email protected]";
var atPosition = email.search("@"); // 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 = "[email protected]";
var found = email.match("house");
document.write(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 = "[email protected]";
var domainID = email.slice(-3);
document.write(doimainID) // domainID value is "gov"
• Example 2:
var email = "[email protected]";
var domainBegin = email.search("@") + 1;
var domainEnd = email.indexOf(".");
var domain = email.slice(domainBegin, domainEnd);
document.write(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 = "[email protected]";
var domainBegin = email.search("@") + 1;
var domainID = email.substring(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 (emailInput.value.search("@") === -1 ||
emailInput.value.lastIndexOf(".") === -1) {
document.write ("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:
string.replace(pattern, text);
• Example:
var email = "[email protected]";
var newEmail = email.replace("president",
"vice.president");
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:
string.concat(value1, value2, ...)

CIM 322 Saka D. 28


Comparing Strings
• Use the comparison operator (===).
• Example:
if (!(password1 === password2) )
document.write(“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";
pattern.test(inventor) ; // true
pattern.test(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;
pattern.test(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 -
[email protected]:
/^[\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 ( !phonePattern.test(phone) ) {
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 ( !datePattern.test(startDate) ) {
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: ex7-4RegExp.html
<!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;"
>&nbsp;</span><br><br>
Password:<input type="password" id="pwd1" size = "20" value="" /> <span id="pwd1_error" style="color:
red;">&nbsp;</span><br><br>
Confirm Password:<input type="password" id="pwd2" size = "20" value="" /> <span id="pwd2_error"
style="color: red;">&nbsp;</span><br><br>
Email:<input type="text" id="email" size = "20" value="" /> <span id="email_error" style="color:
red;">&nbsp;</span>
<p>Format: [email protected]</p>
Phone Number:<input type="text" id="phone" size = "20" value="" /> <span id="phone_error"
style="color: red;">&nbsp;</span>
<p>Format: 0XXX-XXX-XXX </p>
<input type="button" id="butsubmit" value="Register" onClick="validatePatterns()" />
&nbsp;&nbsp;<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 = document.getElementById("name").value;


var password1 = document.getElementById("pwd1").value;
var password2 = document.getElementById("pwd2").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;

if (userName.length < 4)
document.getElementById("name_error").innerHTML = "User name must be at least 4 characters";
else
document.getElementById("name_error").innerHTML = "";

if (password1.length < 4)
document.getElementById("pwd1_error").innerHTML = "Password must be at least 4 characters";
else
document.getElementById("pwd1_error").innerHTML = "";

CIM 322 Saka D. 41


if ( password1 !== password2)
document.getElementById("pwd2_error").innerHTML = "Passwords do not match";
else
document.getElementById("pwd2_error").innerHTML = "";

if (emailPattern.test(email) )
document.getElementById("email_error").innerHTML = "";
else
document.getElementById("email_error").innerHTML = "Invalid email format";

if (phonePattern.test(phone) )
document.getElementById("phone_error").innerHTML = "";
else
document.getElementById("phone_error").innerHTML = "Invalid phone
number";
}
</script>
</body>
</html>

CIM 322 Saka D. 42

You might also like