If you want to highlight whatever that doesn't match a certain pattern, you can use this code. This is much more extensible than trying to modify the regex to negate the matches.
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;
}
Using your case as an example (note that I added the g flag):
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>';
}
});
( )*[ą-źa-z0-9\s]+Put this to regex test and I would like get negative result(?!( ))[^ą-źa-z0-9\s]*this is the better, but not get <- ';'