忽略子字符串的Javascript正则表达式

时间:2010-06-26 10:57:01

标签: javascript regex

背景

我找到了类似的S.O.有关此主题的帖子,但我未能使其适用于我的方案。如果这是一个骗局,请提前申请。

我的意图:

获取字符串中的每个英文单词,并将其转换为html超链接。此逻辑需要忽略以下标记:<br/><b></b>

这是我到目前为止所拥有的。它按照我的预期将英语单词转换为超链接,但没有忽略html标签的逻辑(这是我需要你帮助的地方):

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

示例输入/输出:

示例输入:

this <b>is</b> a test

预期产出:

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

谢谢。

3 个答案:

答案 0 :(得分:0)

除了重新编写HTML之外的问题,我这样做的方法有两个步骤:

  • 首先,以这种或那种方式,提取标签之外的文本
  • 然后只对这些文本进行转换,并保持其他所有内容不受影响

相关问题

答案 1 :(得分:0)

这是一个混合解决方案,可以为您提供innerHTML的性能提升,以及在查找匹配项时不必弄乱HTML字符串的奢侈:

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);

    }

}

输入:

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

过程:

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

输出(为了清晰起见,添加了空白):

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

答案 2 :(得分:0)

这是另一种JavaScript方法。

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);