regular expressions in javascript

22
Eloquent JS Chapter 9 Regular Expressions

Upload: stephanie-slattery

Post on 20-Mar-2017

35 views

Category:

Technology


2 download

TRANSCRIPT

Eloquent JS Chapter 9

Regular Expressions

Literal notation

/ab+c/i;

Constructor

new RegExp('ab+c', 'i');new RegExp(/ab+c/, 'i');Don't forget the normal string escape rules for special characters!

Test

/abc/.test("abcde");=> true/abc/.test("defgh");=> false

Exec

/abc/.exec("abcde");=> ["abc"]/abc/.exec("defgh");=> null

An object with information about the match

/abc/.exec("defabcde").index;=> 3/abcff/.exec("defabcde").index;=> null

Search

"abc0def".search(/\d/);=> 3"abcdef".search(/\d/);=> -1

Replace

"papa".replace("p", "m");=> "mapa"

Replace

"adage".replace(/[ae]/, "u");=> "udage""adage".replace(/[ae]/g, "u");=> "udugu"

Flags (aka modifiers)

i - Perform case-insensitive matchingg - Perform a global matchm - Multiline

Brackets

[abc] - Matches any single character a, b, or c[^abc] - Matches any character except a, b, c[a-c] - Matches any character from a to c

Brackets

(ab|cd) - Matches ab or cd(...) - Captures anything enclosed

Character Classes

. - Any character except newline\d - Any digit\D - Any non-digit

Character Classes

\w - Alphanumeric (word) character\W - Non-alphanumeric character\s - Whitespace character\S - Non-whitespace character

No love for non-Latin characters"éβ".search(/\w/);=> -1Try xRegExp or defining word characters using Unicode.

Boundaries

^ - Start of line$ - End of line\b - At beginning or end of word\B - Not at beginning or end of word

Quantifiers

n+ - Match one or more nn* - Match zero or more n'sn? - Match zero or one n's

Quantifiers

n{3} - Match sequence of 3 n'sn{3,5} - Match sequence of 3 to 5 n'sn{3,} - Match sequence of 3 or more n's

Assertions

x(?=y) - Matches x only if x is followed by yx(?!y) - Matches x only if x is not followed by y

Capture Groups

"Hopper, Grace\nLovelace, Ada".replace(/([\w ]+), ([\w ]+)/g, "$2 $1");

=> "Grace Hopper Ada Lovelace"

Greedy Operators + * ? {}

/<.+>/.exec("<p>Hello world</p>");=> "<p>Hello world</p>"/<.+?>/.exec("<p>Hello world</p>");=> "<p>"