Check if array value is included in string

I am working on some client side validation for the sort contact form, the website is currently not connected, so the server side is not related.

I am trying to create a โ€œword filterโ€ to catch any abuse of obscene language before the form is โ€œsubmittedโ€.

Here is the code, without obscenity ...

function filterInput(str) { var inputFilter = ['word1', 'word2', 'word3']; var arrayLength = inputFilter.length; if (inputFilter.indexOf(str) > - 1) { // Word caught... } else { // Clear... } 

If the user was to enter "word1", he would catch the word. If the user enters the word "word1word2" or "John is word3", he will not catch it.

I originally had a for loop that worked better, but still wouldn't work without spaces between words ("word1word2").

Any input is welcome, I searched, but didnโ€™t meet my needs.

EDIT: So, I came up with a solution too, but, seeing the various ways that this can be achieved, I am curious how this works and also why is the best way better?

Here is what I came up with ...

 function filterInput(str) { var inputFilter = ['word1', 'word2', 'word3']; var arrayLength = inputFilter.length; for (var i = 0; i < arrayLength; i++) { if (str.includes(inputFilter[i])) { window.alert('Message...'); return; } } } 
+5
source share
2 answers

You are looking for some , not indexOf , since you need to do an individual mapping:

 if (inputFilter.some(function(word) { return str.indexOf(word) != -1; })) { // Word caught... } else { // Clear... } 

Or using the arrow function ES2015 + and String.prototype.includes :

 if (inputFilter.some(word => str.includes(word))) { // Word caught... } else { // Clear... } 

some calls the callback several times until the first time returns a true value. If the callback ever returns a true value, some returns true ; otherwise, some returns false . For example, he asks if the predicate function matches "some" elements. ( any may have been a better term, but when added to the built-in components, the TC39 committee should do a lot of work to avoid conflicts with libraries, etc.)

If you ever need to return the actual record, use find , which returns the record, or undefined if not found. If you need its index, use findIndex .


Side note: Just beware that this is notoriously difficult to do well. Beware of the Scunthorpe problem , and of course, people usually just confuse the sequence of letters or replace asterisks or look like filters of this kind of defeat ...

+5
source

you can try something like this: -

 function filterInput(str) { var badWords = ['bad', 'worst']; var isTrue = false; if(str) { for (var i = 0; i < badWords.length; i++) { isTrue = !!(str.replace(/\W|\s/g, '').toLowerCase().indexOf(badWords[i]) + 1); if(isTrue) break; } } return isTrue; } 
0
source

Source: https://habr.com/ru/post/1272281/


All Articles