Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

javascript - jQuery: How to wrap RegEx matched plain text in an anchor tag?

Suppose I have an HTML page that looks something like this:

<html><body>
00123
<input value="00123">
00456
</body></html>

And I want to use javascript/jQuery to make it look like this:

<html><body>
<a href="#00123">00123</a>
<input value="00123">
<a href="#00456">00456</a>
</body></html>

Essentially I want to wrap regular expression matched plain strings in the document with HTML anchor tags. In this example, I want to do something like:

$('body').html($('body').html().replace(/(00d+)/, '<a href="#$1">$1</a>'));

See the jsFiddle with this example: http://jsfiddle.net/NATnr/2/

The problem with this solution is that the text inside the input element is matched and replaced.

Does anyone know how to only match and replace plain text in a document in this manner using javascript/jQuery?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try filtering the body's contents() by nodeType to get only the Text Nodes, then replace them with jQuery-generated anchor elements (any extra text in these nodes will be kept as Text Node):

$('body').contents().filter(function() {
    return this.nodeType === 3;
}).each(function() {
    $(this).replaceWith($(this).text().replace(/(00d+)/g, '<a href="#$1">$1</a>'));
});

Fiddle

As you know, most often it's not a good idea to parse HTML with Regex (look out for the ponies, they are evil), but if you isolate a part of the HTML you want to parse and it follows a relatively simple pattern, it is a viable option.

edit: Included the g flag (global modifier) in your Regex to allow for matching multiple anchors inside a single Text Node.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...