jQuery:如何将RegEx匹配的纯文本包装在锚标签中? [英] jQuery: How to wrap RegEx matched plain text in an anchor tag?
问题描述
假设我有一个HTML页面,如下所示:
< html>< body>
00123
< input value =00123>
00456
< / body>< / html>
我想用javascript / jQuery使它看起来像这样:
< html>< body>
< a href =#00123> 00123< / a>
< input value =00123>
< a href =#00456> 00456< / a>
< / body>< / html>
基本上我想用HTML锚标记在文档中包装正则表达式匹配的普通字符串。在这个例子中,我想做一些事情:
$('body')。html($('body') .html()。replace(/(00\d +)/,'< a href =#$ 1> $ 1< / a>'));
请参阅以下示例中的jsFiddle: http://jsfiddle.net/NATnr/2/
这个解决方案的问题在于文本在输入
元素内部匹配并替换。
有谁知道如何匹配和替换纯文本以这种方式使用javascript / jQuery文件吗? 试试过滤 body
的 contents()
nodeType 以获取文本节点,然后用jQuery生成的锚点元素替换它们(这些节点中的任何额外文本将保留为文本节点):
$('body')。contents()。filter(function(){
return t his.nodeType === 3; ($(this).text()。replace(/(00\d +)/ g,'< a href;
})。each(function(){
$(this).replaceWith =#$ 1> $ 1< / a>'));
});
Fiddle
正如你所知道的,通常用正则表达式解析HTML并不是一个好主意(注意小马,它们是邪恶的),但是如果你隔离了你想要解析的HTML的一部分,遵循相对简单的模式,这是一个可行的选择。
edit:包含 g
标记(全局修饰符)在您的正则表达式中允许在单个文本节点内匹配多个锚。
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(/(00\d+)/, '<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?
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(/(00\d+)/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.
这篇关于jQuery:如何将RegEx匹配的纯文本包装在锚标签中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!