1

「contenteditable」のdivがあります。この div で char をフィルター処理したいのですが、[^ą-źa-z0-9\s]AND NOT ( ) の場合は、色の char を変更する必要があり、パターンに一致しません。たとえば、次のようになります$(this).html(): dfgtąść45 %$# tg ss & k ; ・赤色ボールドチャーに変更をお願いします。

JS:

var t = $(this).html().replace(/<\/?[^>]+>/gi, '').replace(/\s$/, '&nbsp;');
t = t.replace(/(&nbsp;)[^ą-źa-z0-9\s]/ig,function(match){return '<span style="color: red;">' + match + "</span>";});
$(this).html(t);
4

2 に答える 2

1

特定のパターンに一致しないものを強調表示する場合は、このコードを使用できます。これは、一致を否定するために正規表現を変更しようとするよりもはるかに拡張可能です。

function unmatches(regex, str, callback) {

    var result = "";
    var lastAppend = 0;

    var arr;
    var nonMatching;

    while ((arr = regex.exec(str)) != null) {
        nonMatching = str.substring(lastAppend, arr.index);

        if (typeof callback === "function") {
            nonMatching = callback(nonMatching);
        }
        // If a function is not supplied, currently, it output back
        // the input string. It can be extended, though.

        result += nonMatching + arr[0];
        lastAppend = arr.index + arr[0].length;

        // In case the global flag is not set
        // There is at most one match without global flag
        if (!regex.global) {
            break;
        }
    }

    nonMatching = str.substring(lastAppend);

    if (typeof callback === "function") {
        nonMatching = callback(nonMatching);
    }

    result += nonMatching;

    return result;
}

例としてあなたのケースを使用します(私がgフラグを追加したことに注意してください):

var result = unmatches(/(&nbsp;)*[ą-źa-z0-9\s]+/g, "dfgtąść45%$#tg&nbsp;ss&k;", function (m) {
    if (m === "") {
        // Non matching part can be empty string
        return m; // Ignore
    } else {
        // The non-empty string case
        return '<span style="color: red;">' + m + '</span>';
    }
});
于 2013-03-01T11:15:44.320 に答える
1

ここに1つの方法があります

t = t.replace( /(&nbsp;)|(?:(?!&nbsp;)[^ą-źa-z0-9\s])+/ig,
    function ( match, nbsp ) {
        return nbsp ? nbsp : '<span style="color: red;">' + match + "</span>";
});

ただし、この方法で html を操作することはお勧めできません。たとえば、否定された文字クラスに一致する要素属性内の文字は、誤ってspanタグで囲まれます。

于 2013-03-01T11:09:29.487 に答える