1

Background:

I found similiar S.O. posts on this topic, but I failed to make it work for my scenario. Appologies in advance if this is a dupe.

My Intent:

Take every English word in a string, and convert it to a html hyperlink. This logic needs to ignore only the following markup: <br/>, <b>, </b>

Here's what I have so far. It converts English words to hyperlinks as I expect, but has no ignore logic for html tags (that's where I need your help):

text = text.replace(/\b([A-Z\-a-z]+)\b/g, "<a href=\"?q=$1\">$1</a>");

Example Input / Output:

Sample Input:

this <b>is</b> a test

Expected Output:

<a href="?q=this">this</a> <b><a href="?q=is">is</a></b> <a href="?q=a">a</a> <a href="?q=test">test</a>

Thank you.

Alan Moore
  • 68,531
  • 11
  • 88
  • 149
E.W.
  • 237
  • 3
  • 12
  • 2
    Are you working with the DOM? If so, you shouldn't be messing with strings of HTML; instead you should be using the DOM API as it was intended. – James Jun 26 '10 at 11:02
  • Yes working with the DOM. Manipulating strings for performance due to requirements of this particular project. Not to get side tracked here, but I'm using this as a reference on perf: http://www.quirksmode.org/dom/innerhtml.html – E.W. Jun 26 '10 at 11:14

3 Answers3

0

Issues with regexing HTML aside, the way I'd do this is in two steps:

  • First of foremost, one way or another, extract the texts outside the tags
  • Then only do this transform to these texts, and leave everything else untouched

Related questions

Community
  • 1
  • 1
polygenelubricants
  • 348,637
  • 121
  • 546
  • 611
0

Here's a hybrid solution that gives you the performance gain of innerHTML and the luxury of not having to mess with HTML strings when looking for the matches:

function findMatchAndReplace(node, regex, replacement) {

    var parent,
        temp = document.createElement('div'),
        next;

    if (node.nodeType === 3) {

        parent = node.parentNode;

        temp.innerHTML = node.data.replace(regex, replacement);

        while (temp.firstChild)
            parent.insertBefore(temp.firstChild, node);

        parent.removeChild(node);

    } else if (node.nodeType === 1) {

        if (node = node.firstChild) do {
            next = node.nextSibling;
            findMatchAndReplace(node, regex, replacement);
        } while (node = next);

    }

}

Input:

<div id="foo">
    this <b>is</b> a test
</div>

Process:

findMatchAndReplace(
    document.getElementById('foo'),
    /\b\w+\b/g,
    '<a href="?q=$&">$&</a>'
);

Output (whitespace added for clarity):

<div id="foo">
    <a href="?q=this">this</a>
    <b><a href="?q=is">is</a></b>
    <a href="?q=a">a</a>
    <a href="?q=test">test</a>
</div>
James
  • 103,518
  • 28
  • 156
  • 172
  • Thanks J-P, a smart solution. And sorry for not clarifying in my question that although I'm setting a DOM node via InnerHTML, the original source of my raw text is from an AJAX call, so I don't have a DOM node to start with (as your first param requires). – E.W. Jun 26 '10 at 15:12
  • @mrscott, you can still get a DOM structure from an Ajax response though. `function toDom(str) { var d = document.createElement('div'); d.innerHTML = str; return d; }` – James Jun 26 '10 at 16:19
  • Thanks J-P. That does work, but I ran some perf tests on the solution I posted and found that your approach would be about a 10x slower on a large body of text containing a sparse set of
    and tags (which mimicks the real scenario I'm facing).
    – E.W. Jun 26 '10 at 17:28
0

Here's another JavaScript method.

var StrWith_WELL_FORMED_TAGS    = "This <b>is</b> a test, <br> Mr. O'Leary! <!-- What about comments? -->";
var SplitAtTags                 = StrWith_WELL_FORMED_TAGS.split (/[<>]/);
var ArrayLen                    = SplitAtTags.length;
var OutputStr                   = '';

var bStartWithTag               = StrWith_WELL_FORMED_TAGS.charAt (0) == "<";

for (var J=0;  J < ArrayLen;  J++)
{
    var bWeAreInsideTag         = (J % 2) ^ bStartWithTag;

    if (bWeAreInsideTag)
    {
        OutputStr              += '<' + SplitAtTags[J] + '>';
    }
    else
    {
        OutputStr              += SplitAtTags[J].replace (/([a-z']+)/gi, '<a href="?q=$1">$1</a>');
    }
}

//-- Replace "console.log" with "alert" if not using Firebug.
console.log (OutputStr);
Brock Adams
  • 82,642
  • 19
  • 207
  • 268
  • nice solution Brock, but I was hoping for something more concise. I think I have the solution - I'll post it shortly. – E.W. Jun 26 '10 at 15:14