Johan
Johan

Reputation: 35194

Get non-matching characters from regex

I would like to get whatever characters not matching the regex. E.g. "abc123" would return "123", [1,2,3] or something similar.

Is there any built in way to achieve this?

$('input').on('keyup', function(){

    var valid = /^[a-zA-Z\s*]*$/.test(this.value);
    console.log(valid);
});

http://jsfiddle.net/4JrWZ/

Another solution in case someone is intrested:

var x = this.value.split('').filter(function(v){
    return !/[a-zA-Z\s*]+/.test(v);
});

Upvotes: 3

Views: 1231

Answers (3)

tys
tys

Reputation: 29

how does this work with returning not accepted characters separated by comma? reduce will not work in below example example:

const allowedSplChars = /^([a-zA-Z0-9@\-._]{3,50})$/;
let allowedCharacters = allowedSplChars.test(uidInput.value);
var disallowedCharacters = [];
disallowedCharacters = uidInput.value.match(allowedSplChars);

if (allowedCharacters) {
  let splCharErrorNode = document.getElementById("uid_splCharacters");
  if (splCharErrorNode) {
    uidValidationcontainer.removeChild(splCharErrorNode);
  }
} else {
  //remove duplicates
  disallowedCharacters = disallowedCharacters.filter((element, index) => {
    return disallowedCharacters.indexOf(element) === index;
  });

  let splCharErrorNode = document.getElementById("uid_splCharacters");
  if (splCharErrorNode) {
    splCharErrorNode.innerHTML = `${disallowedCharacters.join(", ")}`;
  }
}

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239463

Using reduce

var result = "abc123def123".split(/[a-zA-Z\s*]+/).reduce(function(prev, curr) {
    return curr ? (prev.push(curr), prev) : prev;
}, []);

If you want the result as a string

var result = "abc123def123".split(/[a-zA-Z\s*]+/).reduce(function(prev, curr) {
    return curr ? prev + curr : prev;
}, "");

Upvotes: 4

/[^abc]+/.exec('abc123')

Returns the characters when they do not match either a, b or c.

Upvotes: 1

Related Questions