LEARNING JAVASCRIPT - Trang 280

want to match in a string; there’s no (sensible) way to get those usernames into a

regex literal. This is where the

RegExp

constructor comes in, because it constructs the

regex from a string—which can be constructed dynamically. Let’s consider this

example:

const

users

=

[

"mary"

,

"nick"

,

"arthur"

,

"sam"

,

"yvette"

];

const

text

=

"User @arthur started the backup and 15:15, "

+

"and @nick and @yvette restored it at 18:35."

;

const

userRegex

=

new

RegExp(

`@(?:

${

users

.

join

(

'|'

)

}

)\\b`

,

'g'

);

text

.

match

(

userRegex

);

// [ "@arthur", "@nick", "@yvette" ]

The equivalent literal regex in this example would be

/@(?:mary|nick|arthur|sam|

yvette)\b/g

, but we’ve managed to construct it dynamically. Note that we have to

use double backslashes before the

b

(word boundary metacharacter); the first back‐

slash is to escape the second backslash in the string.

Conclusion

While this chapter has touched on the major points of regexes, it only scratches the

surface of the techniques, examples, and complexities inherent in regexes. Becoming

proficient at regexes is about 20% understanding the theory, and 80% practice. Using

a robust regex tester (such as

regular expressions 101

) can be very helpful when

you’re starting out (and even when you’re experienced!). The most important thing

you can take away from this chapter is an understanding of how a regex engine con‐

sumes input; a lack of understanding in that area is the source of a lot of frustration.

256 | 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.