Returns the first occurrence of unpaired Regex

advertisements

I have a code like this https://jsfiddle.net/tgvtceg3/

var text = "abc(de192/+£,€.&";
var pattern = new RegExp(/^[0-9a-zA-Z\-\,+&.\/]+$/);
var res = pattern.test(text)
alert(res);

I want that code return first occurrence not matched in regex... for example in thi case I want "("

Any suggest are welcome


You can only use another regex to check the text that made your previous validation regex fail to match. Use something like this:

var text = "abc(de192/+£,€.&";
var pattern = /^[0-9a-zA-Z,+&.\/-]+$/;
var res = pattern.test(text)
if (!res) {
   var m=text.match(/[^0-9a-zA-Z,+&.\/-]+/) || [""];
   console.log(m[0]);
}

The /[^0-9a-zA-Z,+&.\/-]+/ regex will find the first occurrence of the char other than those defined in your original regex.

EDIT: Using a dynamic approach to pattern building:

var text = "abc(de192/+£,€.&";
var block = "0-9a-zA-Z,+&./-"; // Define ranges/chars here
var pattern = new RegExp("^[" + block + "]+$"); // Use constructor notation to build the validation regex
var res = pattern.test(text)
if (!res) {
   var m=text.match(new RegExp("[^" + block + "]+")) || [""];
   console.log(m[0]);
}