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?
This from a related answer to a question by bobince:
The final solution ended up looking like this:
See the jsFiddle at work here: http://jsfiddle.net/fr4AL/4/
Thanks to:
Try filtering the
body
'scontents()
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):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.Give this a whirl.... Much cleaner!! ;)