Javascript profanity match NOT replace

天大地大妈咪最大 提交于 2019-12-02 09:00:36

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');

You are matching via a substring comparison. Your Regex needs to be modified to match for whole words instead

How about with fixed regexp:

check = new Regexp('(^|\b)'+badWords.join('|')+'($|\b)', 'gi');

check.test('ass') // true
check.test('suckass') // false
check.test('mass of whore') // true
check.test('massive') // false
check.test('slut is massive') // true

I'm using \b match here to match for word boundry (and start or end of whole string).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!