LEARNING JAVASCRIPT - Trang 276

// close the opening <a> tag

+

'>'

// add the contents

+

parts

[

2

]

// and the closing tag

+

'</a>'

;

}

This function is longer than it needs to be, but we’ve broken it down for clarity. Note

that even in this function, we’re using multiple regexes: one to match the parts of the

<a>

tag, one to do the split (using a regex to identify one or more whitespace charac‐

ters), and one to filter only the attributes we want. It would be much more difficult to

do all of this with a single regex.
Now for the interesting part: using

sanitizeATag

on a block of HTML that might

contain many

<a>

tags, among other HTML. It’s easy enough to write a regex to

match just the

<a>

tags:

html

.

match

(

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

);

But what do we do with it? As it happens, you can pass a function to

String.proto

type.replace

as the replacement parameter. So far, we’ve only be using strings as the

replacement parameter. Using a function allows you to take special action for each

replacement. Before we finish our example, let’s use

console.log

to see how it works:

html

.

replace

(

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

,

function

(

m

,

g1

,

offset

) {

console.log(

`<a> tag found at

${

offset

}

. contents:

${

g1

}

`

);

});

The function you pass to

String.prototype.replace

receives the following argu‐

ments in order:

• The entire matched string (equivalent to

$&

).

• The matched groups (if any). There will be as many of these arguments as there

are groups.

• The offset of the match within the original string (a number).
• The original string (rarely used).

The return value of the function is what gets replaced in the returned string. In the

example we just considered, we weren’t returning anything, so

undefined

will be

returned, converted into a string, and used as a replacement. The point of that exam‐

ple was the mechanics, not the actual replacement, so we simply discard the resultant

string.
Now back to our example…. We already have our function to sanitize an individual

<a>

tag, and a way to find

<a>

tags in a block of HTML, so we can simply put them

together:

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