質問

私は、BBコードの:-)に文字列の:wink:を置換する文字列(一部はHTML)を持っています。しかし、この置換は<pre>以内に起こるべきではありませんが、(タグ内かさえいない)他のタグ内ます。

例えば、私は交換したい

:-)<pre>:-)</pre><blockquote>:-)</blockquote>

:wink:<pre>:-)</pre><blockquote>:wink:</blockquote>

(何も置き換えませんます)私はすでに、次の正規表現でそれを試してみましたが、それは動作しません。

var s = ':-)<pre>:-)</pre><blockquote>:-)</blockquote>';
var regex = /:\-\)(?!(^<pre>).*<\/pre>)/g;
var r = s.replace(regex, ':wink:');

誰かが私を助けてくださいことはできますか? : - )

役に立ちましたか?

解決

これはそれを行うべき: -

var src = ":-)<pre>:-)</pre><blockquote>:-)</blockquote>"

var result = src.replace(/(<pre>(?:[^<](?!\/pre))*<\/pre>)|(\:\-\))/gi, fnCallback)

function fnCallback(s)
{
    if (s == ":-)") return ":wink:"
    return s;
}

alert(result);
任意のpre要素は正規表現に最初のオプションでピックアップし、一度に消費れますので、

これは動作しますが、プロセッサがそれを超えて移動してしまうので、任意の含まれている:-)を一致させることができないことを意味します。

他のヒント

あなたは、このような例えばjQueryのような適切なライブラリを使用する場合は、完全に地獄のような正規表現を避けることができます。

var excludeThese = ['pre'];

// loop over all elements on page, replacing :-) with :wink: for anything
// that is *not* a tag name in the excludeThese array

$('* not:(' + excludeThese.join(',') + ')').each(function() {
    $(this).html($(this).html().replace(/:\-\)/,':wink:'));
});

はちょうどそれは、DOMソリューションを提供する価値があるだろうと思ってます:

例えばます。

var div = document.createElement('div');
div.innerHTML = ":-)<pre>:-)</pre><blockquote>:-)</blockquote>";

replace(div, /:-\)/g, ":wink:", function(){

    // Custom filter function.
    // Returns false for <pre> elements.

    return this.nodeName.toLowerCase() !== 'pre';

});

div.innerHTML; // <== here's your new string!

そして、ここでreplace機能です。

function replace(element, regex, replacement, filter) {

    var cur = element.firstChild;

    if (cur) do {

        if ( !filter || filter.call(cur) ) {

            if ( cur.nodeType == 1 ) {
                replace( cur, regex, replacement );
            } else {
                cur.data = cur.data.replace( regex, replacement );
            }

        }

    } while ( cur = cur.nextSibling );

}

としてみてください VAR正規表現= /: - (?!(^))* )/グラム;

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top