. Prototype: Mở rộng định nghĩa một mảng bằng cách thêm thuộc tính và phương thức
12. Regular Expression
Regular expression: là dãy hay mẫu những kí tự giúp kiểm tra dữ liệu input từ phía người dùng theo một định dạng được yêu cầu.
Tạo Regular Expression: Định dạng
Cách 1: var variable_name = /regular expression/options;
Cách 2: var variable_name = new RegExp("regular expression", "options"); Ở đây, RegExp là một đối tượng.
Các options:
Option Purpose
i Used to ignore case
g Used to match for all occurrences of the pattern in the string
m Used to match over multiple lines
Ví dụ:
var myreg = /love/g;
12. Regular Expression
Các phương thức:
Method What It Does
exec Executes a search for a match in a string and returns an array test Tests for a match in a string and returns either true or false
Ví dụ
<script language = "JavaScript">
var myString="My gloves are worn for wear."; var regex = /love/;
if (regex.test(myString)){
alert("Found pattern love!"); }else{
alert("No match."); }
12. Regular Expression
Các phương thức của String() sử dụng RegExp
Method What It Does
match(regex) Returns array substring in regex or null replace(regex, replacement) Substitutes regex with replacement string search(regex) Finds the starting position of regex in string split(regex) Removes regex from string for each occurrence <script language = "JavaScript">
var matchArray = new Array();
var string="I love the smell of clover.“;
var regex = /love/g;
matchArray=string.match(regex);
document.write("Found "+ matchArray.length +" matches.<br>"); </script>
12. Regular Expression
Getting Control—The Metacharacters:
Regular expression metacharacters là những kí tự mà không tượng trưng cho chúng. Chúng chỉ là các định dạng cho các chuỗi.
Single-character and single-digit metacharacters.
Metacharacter What It Matches
. Matches any character except newline
[a–z0–9_] Matches any single character in set [^a–z0–9_] Matches any single character not in set
\d Matches one digit =[0-9]
\D Matches a non-digit = [^0–9]
\w Matches an alphanumeric (word) character = [A-Za-z0-9_]
12. Regular Expression
<script language=javascript>
var reg_expression = /[A-Z][a-z]eve/; var textString = "He he! Steven";
var result = reg_expression.test(textString);
document.write("<font size='+1'>"+result+"<br>"); if ( result){
document.write("The reg_ex /[A-Z][a-z]eve/ matched the string\""+ textString +"\".<br>");
} else{
alert("No Match!"); }
</script> true
12. Regular Expression
Whitespace Characters
\0 Matches a null character\b Matches a backspace