LEARNING JAVASCRIPT - Trang 268

Note that order doesn’t matter: we could just as easily have said

/[.a-z0-9\-]/

. We

have to escape the dash to match it; otherwise, JavaScript would attempt to interpret

it as part of a range (you can also put it right before the closing square bracket,

unescaped).
Another very powerful feature of character sets is the ability to negate character sets.

Negated character sets say “match everything but these characters.” To negate a char‐

acter set, use a caret (

^

) as the first character in the set:

const

match

=

beer99

.

match

(

/[^\-0-9a-z.]/

);

This will match only the whitespace in our original string (if we wanted to match only

whitespace, there are better ways to do it, which we’ll learn about shortly).

Named Character Sets

Some character sets are so common—and so useful—that there are handy abbrevia‐

tions for them:

Named character set

Equivalent

Notes

\d

[0-9]

\D

[^0-9]

\s

[ \t\v\n\r]

Includes tabs, spaces, and vertical tabs.

\S

[^ \t\v\n\r]

\w

[a-zA-Z_]

Note that dashes and periods are not included in this,
making it unsuitable for things like domain names and CSS
classes.

\W

[^a-zA-Z_]

Probably the most commonly used of these abbreviations is the whitespace set (

\s

).

For example, whitespace is often used to line things up, but if you’re trying to parse it

programmatically, you want to be able to account for different amounts of white‐

space:

const

stuff

=

'hight: 9\n'

+

'medium: 5\n'

+

'low: 2\n'

;

const

levels

=

stuff

.

match

(

/:\s*[0-9]/g

);

(The

*

after the

\s

says “zero or more whitespace,” which we’ll learn about shortly.)

244 | Chapter 17: Regular Expressions

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.