简体   繁体   中英

JavaScript - Regex to remove code / special characters / numbers etc

Answer @Wiktor Stribiżew suggested:

function myValidate(word) {
    return (word.length === 1 || /[^A-Z]/i.test(word)) ? true : false;
    }

Hello during the creation of an array I have a function that will not allow words with certain characters etc to be added to the array

    function myValidate(word) {
        // No one letter words
        if (word.length === 1) {
            return true;
        }
        if (word.indexOf('^') > -1 || word.indexOf('$') > -1) {
            return true;
        }
        return false;
    }

It seems like not the proper way of going about this and ive been looking into a regex that would handle it but have not been successful implementing it, tried numerous efforts like:

if (word.match('/[^A-Za-z]+/g') ) {
            return true;
        }

can some one shed some light on the proper way of handling this?

I suggest using a simpler solution:

 function myValidate(word) { return (word.length === 1 || /[^AZ]/i.test(word)) ? false : true; } var words = ["Fat", "Gnat", "x3-2741996", "1996", "user[50]", "definitions(edit)", "synopsis)"]; document.body.innerHTML = JSON.stringify(words.filter(x => myValidate(x)));

Where:

  • word.length === 1 checks for the string length
  • /[^AZ]/i.test(word) checks if there is a non-ASCII-letter symbol in the string

If any of the above condition is met, the word is taken out of the array. The rest remains.

EDIT: using test instead of match

You want to use test() because it returns a bool telling you if you match the regex or not. The match() , instead, always returns the matched elements. Those may be cast to true by coercion. This is not what you want.

To sum it all up you can just use this one-liner (no if needed and no quotes either, cannot get any simpler):

return word.test(/^[a-zA-Z][a-zA-Z]+$/); // two letter words

You should whitelist characters instead of blacklisting. That's one of the principles in security. In your case, don't tell what is wrong, but tell what is right:

if (word.test('/^[a-zA-Z]+$/')) { // two letter words
    return false;
}

This will return false for all words that contain ONLY [a-zA-Z] characters. I guess this is what you want.

Your regex, instead, looked for illegal characters by negating the character group with the leading ^ .


Two recommendations:

  1. Just use regex in a positive way (without negation) and it'll be a lot easier to understand.

  2. Also, validation functions normally return true for good data and false for bad data.

It is more readable this way:

if (validate(data))
{
    // that's some good data we have here!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM