jquery - Javascript dynamic regex -


after looking here came patter test array of words against string.

$.each(data, function(index, val) {     var pattern = new regexp('?:^|\s'+ val + '?=\s|$', 'g');     console.log(pattern.test(comment));     if (!pattern.test(comment)) {                                       yay = true;          } }); 

the problem here returns true time. suggestions? thanks!

from jsfiddle, forked , created 1 of own, , solution (with regular expression comments) works quite well, once minor typos cleared up. however, much, cleaner , faster. here's did differently:

$('#send-btn').on('click',function(){     $('#error').hide();     var pattern = new regexp('\\b(' + list.join('|') + ')\\b', 'i');     var comment = $('#comment').val();     if(pattern.test(comment)){         $('#error').show();     }; }); 

specifically, pattern generated takes advantage of javascript's array.join (javascript built-in) pastes array of strings prescribed interstitial string. builds string of search words appended regular expressions alternator (|). surrounding group parentheses contain alternation, can apply word boundary regular expression(\b) either end make sure we're matching entire words. in other news: don't need g (global) modifier if you're doing simple test. may need in other applications - such if wanted highlight offending word - dropped it. should using i modifier case-insensitive behaviour.

the biggest upside could, if wanted to, choose define regular expression outside function, , you'll see pretty significant speed gains.

downside: there diminishing returns list of foul words gets longer. given this benchmark, it'll while before way better (a long while).

note

you should made aware ought escape words before use them in regular expression - in list, instance 'a.s.s' match 'alsls'. while is gibberish, it's not swear word, , can see how such problem extrapolate finding profanity there none. however, may choose outside function, perhaps leveraging power of regular expressions in word definitions (define '[a@][$s]{2}' instead of 'ass', '@ss', 'a$s', 'as$', '@$s', '@s$', 'a$$', , '@$$'), i'm not going address here.

good luck, , happy regexing.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -