LEARNING JAVASCRIPT - Trang 273

There’s more than one way to fix this example, but because we’re talking about greedy

versus lazy matching, we’ll solve it by making the repetition metacharacter (

*

) lazy

instead. We do so by following it with a question mark:

input

.

replace

(

/<i>(.*?)<\/i>/ig

,

'<strong>$1</strong>'

);

The regex is exactly the same except for the question mark following the

*

metachar‐

acter. Now the regex engine thinks about this regex this way: “I’m going to stop as

soon as I see an

</i>

.” So it lazily stops matching every time it sees an

</i>

without

scanning further to see if it could match later. While we normally have a negative

association with the word lazy, that behavior is what we want in this case.
All of the repetition metacharacters—

*

,

+

,

?

,

{n}

,

{n,}

and

{n,m}

—can be followed

with a question mark to make them lazy (though in practice, I’ve only ever used it for

*

and

+

).

Backreferences

Grouping enables another technique called backreferences. In my experience, this is

one of the least used regex features, but there is one instance where it comes in handy.

Let’s consider a very silly example before we consider a truly useful one.
Imagine you want to match band names that follow the pattern XYYX (I bet you can

think of a real band name that follows this pattern). So we want to match PJJP,

GOOG, and ANNA. This is where backreferences come in. Each group (including

subgroups) in a regex is assigned a number, from left to right, starting with 1. You can

refer to that group in a regex with a backslash followed by a number. In other words,

\1

means “whatever group #1 matched.” Confused? Let’s see the example:

const

promo

=

"Opening for XAAX is the dynamic GOOG! At the box office now!"

;

const

bands

=

promo

.

match

(

/(?:[A-Z])(?:[A-Z])\2\1/g

);

Reading from left to right, we see there are two groups, then

\2\1

. So if the first group

matches

X

and the second group matches

A

, then

\2

must match

A

and

\1

must match

X

.

If this sounds cool to you but not very useful, you’re not alone. The only time I think

I have ever needed to use backreferences (other than solving puzzles) is matching

quotation marks.
In HTML, you can use either single or double quotes for attribute values. This ena‐

bles us to easily do things like this:

// we use backticks here because we're using single and
// double quotation marks:

const

html

=

`<img alt='A "simple" example.'>`

+

`<img alt="Don't abuse it!">`

;

const

matches

=

html

.

match

(

/<img alt=(?:['"]).*?\1/g

);

Backreferences | 249

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.