简体   繁体   中英

javascript regular expression match exclude space and special charcters

Am having set of restricted keywords

in my comment / message posting block should not allow the restricted words which i defined.

Eg: keyword is "facebook".

facebook, FaceBook, facebook, f*a*c*e*b*o*o*k, facebook, (face book),'facebook' these words should not allow to post.

Any ideas using regular expression in java script would be appreciated.

I'm not sure this is a good idea but all the words you show could be detected using

var isFacebook = /f\W*a\W*c\W*e\W*b\W*o\W*o\W*k/i.test(str);

Note that you can easily generate such a pattern from a word, which makes it easy to extend with a dictionary :

var r = new RegExp("facebook".split('').join('\\W*'), 'i');

Try this regex:

f[^a-zA-Z0-9]?a[^a-zA-Z0-9]?c[^a-zA-Z0-9]?e[^a-zA-Z0-9]?b[^a-zA-Z0-9]?o[^a-zA-Z0-9]?o[^a-zA-Z0-9]?k

It will match the following:

facebook
f a c e b o o k
f-a-c-e-b-o-o-k
f*a*c*e*b*o*o*k

But will not match the following:

facesbooks
ffaceebbookss

You can use a regex similar to the one provided to detect such words.

If you mean that you want to filter a given word, surrounded by word-boundary and with possible special characters separating the word's letters:

var keyword="facebook",
    specialCharClass="[*-]",
    regex;
regex= new RegExp("\\b" + keyword.replace(/(?:)/g,specialCharClass+'?') + "\\b",'g');

"hi(facebo-ok)pie".replace(regex,"__________"); //returns "hi(__________)pie"

However, there are always ways around word filters (faceb00k for example).

If your goal is to block, not to strip, I would implement this as a two step process.

  1. Strip out all non-text, translate 1337 to normal text (say leet), etc
  2. check for forbidden words, and block if any go wrong

That way you seperated your concerns of blocking a certain list of words, and making sure that you're checking the actual text.

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