Professional Documents
Culture Documents
Javascript (Regular Expressions) : Erick Kurniawan, S.Kom
Javascript (Regular Expressions) : Erick Kurniawan, S.Kom
Regular Expressions
Diperkenalkan pada javascript versi 1.2 Menggunakan RegExp object Digunakan untuk mengecek inputan user (argumen yang diinputkan user) Syntax dari regular expressions biasanya diapit / dan / Contoh
var pattern = /http/;
Regular Expressions
Dapat dibuat dengan menggunakan RegExp() konstruktor Contoh 1:
var pattern = new RegExp("http"); var patternIgnoringCase = new RegExp("http", "i");
Contoh 3:
var pattern = /^http$/; pattern.test("HTTP://WWW.W3C.ORG/"); //return false
Repetition Quantifiers
var pattern = /ab?c/; var pattern = /ab{5}c/; var pattern = /abbbbbc/; var pattern = /ab{5,7}c/; var pattern = /ab{3,}c/;
Repetition Quantifiers
Character * + ? {m, n} {m, } {m} Meaning Match previous item zero or more times. Match previous item one time or more. Match previous item zero or one times. Match previous item at minimum m times, but no more than n times. Match previous item m or more times. Match previous item exactly m times.
Character Classes
var pattern var pattern var pattern var pattern var pattern var pattern no telp? = = = = = = /[pbm]ill/; /[1234567890]+/; /[0-9]+/; /[a-z]/; /[a-zA-Z0-9]/; /^[a-z][a-z0-9_-]*/i; //untuk
Alternatives
var pattern = /^(http|ftp|https)/; var pattern = /(James|Jim|Charlie) Brown/;
Character Classes
Character [chars] [^chars] . \w \W \s \S \d \D \b \B [\b] Meaning Any one character indicated either explicitly or as a range between the brackets. Any one character not between the brackets represented explicitly or as a range. Any character except newline. Any word character. Same as [a-zA-Z0-9_]. Any non-word character. Same as [^a-zA-Z0-9_]. Any whitespace character. Same as [ \t\n\r\f\v]. Any non-whitespace character. Same as [^ \t\n\r\f\v]. Any digit. Same as [0-9]. Any non-digit. Same as [^0-9]. A word boundary. The empty space between a \w and \W. A word non-boundary. The empty space between word characters. A backspace character.
Examples
Regular Expression /\Wten\W/ /\wten\w/ /\bten\b/ /\d{1,3}\.\d{1,3}\.\ d{1,3}\.\d{1,3}/ Matches ten aten1 ten 128.22.45.1 Does Not Match ten, tents ten, 1ten attention, tensile, often abc.44.55.42 128.22.45.