Christian Stewart
Christian Stewart

Reputation: 15519

Filter characters in this RegEx

I have this regular expression to match a valid name: /^['"\s\-.*0-9\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(name)

I'm having trouble figuring out how to transform this match style regex into one designed to filter out invalid characters using replace.

Ideally I would like to be able to take an invalid name in name, run it through the replace to replace any invalid characters, and then have the original test return true no matter what (as invalid characters will be filtered out).

Upvotes: 0

Views: 442

Answers (2)

Ke Vin
Ke Vin

Reputation: 2024

/^['"\s\-.*0-9\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/

The + at the end tells you to match a at least 1 or multiple characters of the types inside the brackets. The ^ at the beginning in combination with the $ at the end tells to match the whole input from its start to its end. So given regex matches a string consisting of only the characters of the set.

What you want is this:

/[^'"\s\-.*0-9\u00BF-\u1FFF\u2C00-\uD7FF\w]/g

[^] means to NOT match whatever is inside the brackets and is the opposite of [].

Upvotes: 1

univerio
univerio

Reputation: 20518

Just use a negated character class by adding a ^ in front:

name.replace(/[^'"\s\-.*0-9\u00BF-\u1FFF\u2C00-\uD7FF\w]/g, "")

Example:

var name = "'41%!\u2000abc";
var sanitized = name.replace(/[^'"\s\-.*0-9\u00BF-\u1FFF\u2C00-\uD7FF\w]/g, "");
console.log(/^['"\s\-.*0-9\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(name)); // false
console.log(/^['"\s\-.*0-9\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(sanitized)); // true

Upvotes: 1

Related Questions