Javascript profanity match NOT replace

前端 未结 3 1340
天涯浪人
天涯浪人 2021-01-28 10:46

I am building a very basic profanity filter that I only want to apply on some fields on my application (fullName, userDescription) on the serverside

3条回答
  •  感情败类
    2021-01-28 11:13

    The test method sets the lastIndex property of the regex to the current matched position, so that further invocations will match further occurrences (if there were any).

    check.lastIndex // 0 (init)
    filterString('ass'); // true
    check.lastIndex // 3
    filterString('ass'); // false
    check.lastIndex // now 0 again
    

    So, you will need to reset it manually in your filterString function if you don't recreate the RegExp each time:

    function filterString(string) {
        check.lastIndex = 0;
        return check.test(string);
    }
    

    Btw, to match only full words (like "ass", but not "asster"), you should wrap your matches in word boundaries like WTK suggested, i.e.

    var check = new Regexp("\\b(?:"+badWords.join('|')+")\\b", 'gi');
    

提交回复
热议问题