如果要突出显示与特定模式不匹配的任何内容,可以使用此代码。这比尝试修改正则表达式来否定匹配项更具可扩展性。
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(/( )*[ą-źa-z0-9\s]+/g, "dfgtąść45%$#tg 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>';
}
});