2

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

Francesco G.
  • 679
  • 3
  • 13
  • 32

4 Answers4

2

You can have a negative regex to define and then just use string.match(regex) to get all matches.

To get first mismatch, just do result[0]

Regex: /[^0-9a-zA-Z\-\,+&.\/]/g

This will match all characters except mentioned ones.

var text = "abc(de192/+£,€.&";
var pattern = new RegExp(/[^0-9a-zA-Z\-\,+&.\/]/g);
var res = text.match(pattern)
console.log(res);
console.log(res[0]);
Rajesh
  • 24,354
  • 5
  • 48
  • 79
2

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]);
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

As described in this question

You need to make your regular expression non-greedy, because by default, "(.*)" will match all of "file path/level1/level2" xxx some="xxx".

So I hope this will help, by adding '?' to the end of your regex to make it nongreedy, and move the ^ to the character section in the regex. for debug regex, I use regex101.com which is great.

var text = "abc(de192/+£,€.&";
var pattern = new RegExp(/[^0-9a-zA-Z\-\,+&.\/]?/);
var res = pattern.test(text)
alert(res);
Community
  • 1
  • 1
Eyal Cohen
  • 1,188
  • 2
  • 15
  • 27
0

You can just add a ^ into the beginning of the character case to look for any character not inside it:

var text = "abc(de192/+£,€.&";
var pattern = new RegExp(/([^0-9a-zA-Z\-\,+&.\/]+)/);
var res = pattern.exec(text);
console.log(res ? res[0] : undefined);
Moishe Lipsker
  • 2,974
  • 2
  • 21
  • 29
  • Sorry but please check other answers as this has been covered in more than 1 answer. – Rajesh Mar 09 '17 at 08:38
  • @Rajesh This answer also briefly explains the logic as well as handles a case where `res` has no matches (besides for using `exec` instead and omitting the `g` modifier which isn't needed). BTW I wrote this before seeing your answer. – Moishe Lipsker Mar 09 '17 at 08:44