Checking if words match with or without spaces - javascript
I have a code, I'll just give a small example below. Though what it does is gets the users name, then checks for other context. Then I check them versus eachother, and my entire script works besides this one point and it's not giving a leeway.
var getName= $('#element').text(),
uName =getName.replace("Welcome ",""),
loggedIn = newMember.replace(membersList,"");
if(loggedIn !== uName)
{
//run other codes
}
Though when I do this it's still running the code. Am I writing the conditional wrong?
From your question title, I assume your concern is that the string comparison of loggedIn !== uName is being impacted by leading and/or trailing spaces on one or the other.
You need to use trim(), and would be wise to validate the presence of the prototype before using it (see this answer for an explanation).
Your code would now be:
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
var getName= $('#element').text(),
uName =getName.replace("Welcome ","").trim(),
loggedIn = newMember.replace(membersList,"").trim();
if(loggedIn !== uName)
{
//run other codes
}
Related
If statement in a switch
I am working on a question for a course for learning javascript. I am running into trouble trying to add an if statement inside of a switch. I currently have: var user = prompt("Are you ready for battle?!").toUpperCase(); switch(user) { case'YES': if(YES && NO) { console.log("Great, let's do it."); } else { console.log("Bye"); } console.log("Great! It will be a long exciting battle."); break; case'NO': console.log("Come back when you are ready."); break; case'MAYBE': console.log("Go away. This is only for the brave"); break; default: console.log("You obviously do not belong here. It was a simple yes/no question.") } The question is this: Add some if/else statements to your cases that check to see whether one condition and another condition are true, as well as whether one condition or another condition are true. Use && and || at least one time each. The error I am getting is this: ReferenceError: YES is not defined What can I put in the if's condition to make this work or how do I define YES?
It would appear that you have two problems working against you here. First is the issue pointed out in comments that you're treating YES and NO like variables, and they aren't. To avoid robbing you of the opportunity to learn by providing a corrected version of your code, I'll only give relevant examples. var word = "test"; // If we compare against the string literally, it will have an error // because it's looking for a variable with that name. if (word === test) { } // ReferenceError: test is not defined // we fix this by quoting what we're comparing against if (word === "test") { } // Code inside the block would be executed :) // But what about checking the value of "test" by itself? // A string is "truthy", meaning that it passes the conditional test always. if ("test") { } // Code would be executed always regardless of the content of var word // Stringing multiple constants together doesn't make sense if ("test" && "word") { } // This is equivalent... if (true && true) { } // ... to this, which doesn't make sense This brings us to the second problem you're trying to solve. The requirements for your problem specify checking if one condition AND another are true, as well as one condition OR another. The problem is that you only have one conditional to check: the status of the variable user. It only makes sense to test the condition of something if you don't know what it is. Input received from a user is a perfect example. So I'd recommend that you take more inputs from the user such as name, age, gender, shoe size, or anything else. You can then check conditions as follows: // You would need to store user input in variables username and age previously... if (username === "vastlysuperiorman" && age < 13) { console.log("You're awfully young!"); } // Or to only allow people within an age range... if (age < 13 || age > 31) { console.log("You must be between 13 and 31 years old to play this game!"); } Once you have multiple conditions to check, you can check them anywhere--inside a function, inside a case statement, inside another if. It doesn't matter. Just add an if block and test the conditions. :)
Form handling and validation in pure JavaScript
My intention is to get your thoughts and criticism about the script below, as regards the algorithm's design, performance and cross-browser compatibility. I have just started getting into JavaScript having missed out on its awesomeness for quite a while. My background and experience is in developing C/C++/PHP based RESTful backends. In order to understand the language and the right way of using it, I decided to do something which I am sure has been done many times before. But learning to use a new language and paradigm often entails pain anyway. This is my attempt to create a normal form processing and validation script/ function. In order to reduce complexity and keep code simple/clean, I decided to use HTML5 Custom Data Attributes (data-*) to assign metadata for each element in the form: Data-Required: True or False. If set to true, this parameter makes the form-field required and so it cannot be empty. A value set to false indicates that the field is optional. Default is false.> Data-Type: Type of validation to be performed. Examples include 'email', 'password', 'numbers' or any other 'regexp'. A fairy simple example of such a form would be: <form action="postlistings" id="postlistings" enctype='multipart/form-data' method="post" class="postlistings"> <ul class="login-li"> <li> <input class="title" name="title" type="title" id="title" data-required="true" data-type="title"></a> </li> <li> <textarea name="body" id="elm1" class="elm1" name="elm1" data-type="body" data-required="true" > </textarea> </li> <li> <span class="nav-btn-question">Add Listing</span> </li> </ul> </form> Reminder: This is my first piece of JavaScript code. The idea is to call Form while passing the form name to retrieve and validate all the field values in one loop for performance. The validation involves two steps as can be guessed from the Data-* attributes described above: i. Check for required form fields. In case the values fail to meet step 1 requirement, an error message from configuration is pulled for the specific form value. Thus, for all values that fail to meet this requirement, an array of error messages are collected and passed on to the View. ii. Perform respective validations. Validations are only performed if all the values passed step 1. Otherwise, they follow the same steps as indicated in 1 above. function Form(){ var args = Array.prototype.slice.call(arguments), formName = args[0], callback = args.pop(), userError = [{type: {}, param: {}}], requiredDataParam = 'required', typeDataParam = 'type', form = document.forms[formName], formLength = form.length || null, formElement = {id: {}, name: {}, value: {}, required: {}, type: {}}; function getFormElements(){ var num = 0; var emptyContent = false; for (var i = 0; i < formLength; i += 1) { var formField = form[i]; formElement.id[i] = inArray('id', formField) ? formField.id : null; formElement.name[i] = inArray('name', formField) ? formField.name : null; formElement.value[i] = inArray('value', formField) ? formField.value : null; formElement.required[i] = getDataAttribute(formField, requiredDataParam); formElement.type[i] = getDataAttribute(formField, typeDataParam); if (formElement.required[i] === true){ if(!formElement.type[i]) { error('Validation rule not defined!'); } else if (!formElement.value[i]) { userError[num++] = {'type': 'required', 'param': form[i]}; emptyContent = true; } } if (emptyContent === false) { // Perform validations only if no empty but required form values were found. // This is so that we can collect all the empty // inputs and their corresponding error messages. } } if (userError) { // Return empty form errors and their corresponding error messages. } return formElement; }; // Removed the getFormParam function that was not used at all. return { getFormElements: getFormElements } }; Two outside functions that are used in the JS script above (from JQuery source): var inArray = function(elem, array){ if (array.indexOf){ return array.indexOf(elem); } for (var i = 0, length = array.length; i < length; i++){ if (array[i] === elem){ return i; } } return -1; } // This is a cross-platform way to retrieve HTML5 custom attributes. // Source: JQuery var getDataAttribute = function(elem, key, data) { if (data === undefined && elem.nodeType === 1) { data = elem.getAttribute("data-" + key); if (typeof data === "string") { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : !CheckType.isNaN ? parseFloat(data) : CheckType.rbrace.test(data) ? parseJSON(data) : data; } else { data = undefined; } } return data; } An example of Config Error messages can be set as follows: var errorMsgs = { ERROR_email: "Please enter a valid email address.", ERROR_password: "Your password must be at least 6 characters long. Please try another", ERROR_user_exists: "The requested email address already exists. Please try again." }; As I post this for your review, please ignore any styling conventions that I might not have followed. My intention is to get your expert reviews on anything I should be doing different or could do better concerning the code itself, and the algorithm. Besides the styling conventions, all criticism and questions are welcome.
First I'd like to clear up a common misconception. Forgive me if you already understand this clearly; maybe it will be helpful for someone else. Learning and using jQuery or a similar library does not preclude or conflict with learning the JavaScript language. jQuery is simply a DOM manipulation library which takes away many of the pain points of using the DOM. There's plenty of room to learn and use JavaScript, the language, even if you use a library to abstract away some of the DOM details. In fact, I would argue that using the DOM directly is likely to teach bad JavaScript coding habits, because the DOM is very much not a "JavaScript-ish" API. It was designed to work identically in JavaScript and Java and potentially other languages, and so it completely fails to make good use of the features of the JavaScript language. Of course as you said, you're using this as a learning exercise; I just don't want you to fall into the trap that I've seen many people fall into of thinking, "I don't want to learn jQuery, because I want to learn JavaScript instead!" That's a false dichotomy: you have to learn JavaScript in either case, and using jQuery for the DOM doesn't interfere with that at all. Now some details... While it's OK to quote property names in an object literal and when you reference the properties, it's customary - and more readable - not to quote them when they are valid JavaScript names. e.g. in your formElement object formElement = { id: {}, name: {}, value: {}, required: {}, type: {} }; (there was a missing semicolon at the end there too) and where you use the names you can do: formElement.id[i] = ... formElement.name[i] = ... etc. Don't run your loops backwards unless the program logic requires it. It doesn't make the code faster except possibly in the case of an extremely tight loop, and it makes it unclear whether you're just prematurely optimizing or actually need the backwards loop. Speaking of optimization, that loop has several inArray() calls. Since each of those loops through an array, that could be more of a performance impact than the outer loop. I imagine these arrays are probably pretty short? So performance wouldn't matter at all anyway, but this is something to think about in cases where you have longer arrays and objects. In some cases you can use an object with property names and values for a faster lookup - but I didn't look closely enough at what you're doing to suggest anything. In any case, you're using inArray() wrong! But not your fault, that is a ridiculously named function in jQuery. The name clearly suggests a boolean return value, but the function returns the zero-based array index or -1 if the value is not found. I strongly recommend renaming this function as indexOf() to match the native Array method, or arrayIndex(), or some such. That same loop has form[i] repeated numerous times. You could do this at the top of the loop: var field = form[i]; and then use field throughout, e.g. field.id instead of form[i].id. This is generally faster, if it matters (which it probably doesn't here), but more importantly it's easier to read. Do not use strict boolean comparisons like if( foo === true ) and if( bar === false) unless you really need to - and those cases are rare. The code sends a signal to the reader that there is something going on that's different from the usual boolean test. The only time these particular tests should be used is when you have a variable that may contain a boolean value or may contain some other type of value, and you need to distinguish which is which. A good example of a case where you should use tests like these is an optional parameter that defaults to true: // Do stuff unless 'really' is explicitly set to false, e.g. // stuff(1) will do stuff with 1, but stuff(1,false) won't. function stuff( value, really ) { if( really === false ) { // don't do stuff } else { // do stuff } } That specific example doesn't make a lot of sense, but it should give you the idea. Similarly, an === true test could be used in a case where need to distinguish an actual boolean true value from some other "truthy" value. Indeed, it looks like this line is a valid case for that: if (formElement['required'][i] === true){ given that if (formElement['required'][i] comes from the getDataAttribute() function which may return a boolean or other type. If you are just testing for truthiness, though - and this should be most of the time - simply use if( foo ) or if( ! foo ). Or similarly in a conditional expression: foo ? x : y or !foo ? x : y. The above was a long-winded way of saying that you should change this: if (empty_content === false) { to: if (!empty_content) { Your getFormParam() function goes to some work to convert an undefined result to null. There is usually no reason to do this. I don't see any place where that function is called, so I can't advise specifically, but in general you'd be testing for truthiness on something like this, so null and undefined would both be treated as false. Or in cases where you do need to distinguish null/undefined from other values (say, an explicit false), you can easily do it with != null or == null. This is one case where the "looser" comparison performed by == and != is very useful: both null and undefined evaluate the same with these operators. You asked to ignore coding style, but one little suggestion here: You have a mix of camelCaseNames and names_with_underscores. In JavaScript, camelCaseNames are more idiomatic for function and variable names, with PascalCaseNames for constructor functions. Of course feel free to use underscores where they make more sense, for example if you're writing code that works with database columns in that format you may want your variable names to match the column names. Hope that helps! Keep up the good work. Update for your new code I'm having a bit of trouble following the logic in the code, and I think I know part of the reason. It's a combination of naming conventions and inside-out objects. First, the name formElement is really confusing. When I see element in JavaScript, I think of either a DOM element (HTMLElement) or an array element. I'm not sure if this formElement represents one or the other or neither. So I look at the code to figure out what it's doing, and I see it has id:{}, name:{}, ... properties, but the code later treats each of those as an Array and not an Object: formElement.id[i] = ... formElement.name[i] = ... formElement.value[i] = ... formElement.required[i] = ... formElement.type[i] = ... (where i is an integer index) If that code is right, those should be arrays instead: id:[], name:[], .... But this is a red flag. When you see yourself creating parallel arrays in JavaScript, you're probably doing it wrong. In most cases you're better off replacing the parallel arrays with a single array of objects. Each of the objects in that array represents a single slice through all your parallel arrays, with a property for each of the previous arrays. So, this object (where I've made the correction from {} to [] to match its current use): formElement = { id: [], name: [], value: [], required: [], type: [] }; should be: formInfo = []; and then where you have the code that goes: formElement.id[i] = ...; formElement.name[i] = ...; formElement.value[i] = ...; formElement.required[i] = ...; formElement.type[i] = ...; It should be: var info = { id: ..., name: ..., value: ..., required: ..., type: ... }; formInfo.push( info ); and adjust the rest of the code to suit. For example: formElement.required[i] would be: formInfo[i].required or even simpler since it's in the same function: info.required And note: I'm not saying info and formInfo are great names :-) they are just placeholders so you can think of a better name. The main idea is to create an array of objects instead of a set of parallel arrays. One last thing and then I'm out of time for now. That getDataAttribute() function is a complicated little piece of work. You don't need it! It would be simpler would just call the underlying function directly where you need it: var info = { ... required: formField.getAttribute('data-required') === 'true', type: formField.getAttribute('data-type') }; This also gives you full control of how the attributes are interpreted - as in the === 'true' test above. (This gives you a proper boolean value, so when you test the value later you don't have to use === true on it.) On a stylistic note, yes, I did hard code the two 'data-xxxx' names right there, and I think that's a better and more clear way to do it.. Don't let your C experience throw you off here. There's no advantage to defining a string "constant" in this particular case, unless it's something that you want to make configurable, which this isn't. Also, even if you do make a string constant, there's a minor advantage to having the complete 'data-whatever' string instead of just 'whatever'. The reason is that when somebody reads your HTML code, they may see a string in it and search the JS code for that string. But when they search for data-whatever they won't find it if the data- prefix is automagically prepended in the JS code. Oh, I forgot one last thing. This code: function Form(){ var args = Array.prototype.slice.call(arguments), formName = args[0], callback = args.pop(), is working way too hard! Just do this instead: function Form( formName, callback ) { (and keep the var for the remaining variable declarations of course)
I cannot add comments yet so here is a little tip. I would separate the getFormElements() into smaller private functions. And I would add the errorMsgs to the Form function. But for a first script in JavaScript, it is very impressive. This is actually the real reason I respond. I think it deserves more upvotes, and I would be very interested in a JS ninja responding to this question. Good luck!
What unicode character I can use to "flag" a string?
I want to represent an object that has several text properties, every one representing the same text value but in different languages. In case the user modifies a single field, the other fields should be revised, and I'm thinking on adding a single Unicode character at the beginning of the string of the other fields, and then to check for fields that need attention, I just have to check the value at obj.text_prop[0]. Which Unicode character can I use for this purpose? Ideally, it would be non-printable, supported in JS and JSON.
Such flagging should be done some other way, at a protocol level other than character level. For example, consider as making each language version an object rather than just a string; the object could then have properties such as needsAttention in addition to the property that contains the string. But in case you need to embed such information into a string, then you could use ZERO WIDTH SPACE U+200B. As such it means line break opportunity, but this should not disturb here. The main problem is probably that old versions of IE may display it as a small rectangle. Alternatively, you could use a noncharacter code point such as U+FFFF, if you can make sure that the string is never sent anywhere from the program without removing this code point. As described in Ch. 16 of the Unicode Standard, Special Areas and Format Characters, noncharacter code points are reserved for internal use in an application and should never be used in text interchange.
I would suggest you not to use strange characters in the beginning of the line. You can implement something like this: <script type="text/javascript"> function LocalizationSet(){}; LocalizationSet.prototype.localizationItems = []; LocalizationSet.prototype.itemsNeedAttention = []; LocalizationSet.prototype.setLocalization = function(langId, text) { this.localizationItems[langId] = text; this.itemsNeedAttention[langId] = true; } LocalizationSet.prototype.getLocalization = function(langId) { return this.localizationItems[langId]; } LocalizationSet.prototype.needsAttention = function(langId) { if(this.itemsNeedAttention[langId] == null) { return false; } return this.itemsNeedAttention[langId]; } LocalizationSet.prototype.unsetAttentionFlags = function() { for(var it in this.itemsNeedAttention) { this.itemsNeedAttention[it] = false; } } //Example var set = new LocalizationSet(); set.setLocalization("en","Hello"); set.setLocalization("de","Willkommen"); alert(set.needsAttention("en")); alert(set.needsAttention("de")); set.unsetAttentionFlags(); alert(set.needsAttention("en")); set.setLocalization("en","Hi"); alert(set.needsAttention("en")); //Shows true,true,false,true </script>
A function to detect common passwords and prevent user from setting it?
I'm working on user passwords security and one of the important things for me is to force the user to reenter a password when the password is found in most common passwords list. What would be the best way to do this?
I came up to this method and it's working fine. It detects 500 most common passwords. Returning 'true' if there is an entry of blacklisted password in the password field. I hope it will help someone. function passwordPreventCommon(commonValue) { var commonPassword = Array("123456","password","12345678","1234","pussy","12345","dragon","qwerty","696969","mustang","letmein","baseball","master","michael","football","shadow","monkey","abc123","pass","6969","jordan","harley","ranger","iwantu","jennifer","hunter","2000","test","batman","trustno1","thomas","tigger","robert","access","love","buster","1234567","soccer","hockey","killer","george","sexy","andrew","charlie","superman","asshole","dallas","jessica","panties","pepper","1111","austin","william","daniel","golfer","summer","heather","hammer","yankees","joshua","maggie","biteme","enter","ashley","thunder","cowboy","silver","richard","orange","merlin","michelle","corvette","bigdog","cheese","matthew","121212","patrick","martin","freedom","ginger","blowjob","nicole","sparky","yellow","camaro","secret","dick","falcon","taylor","111111","131313","123123","bitch","hello","scooter","please","","porsche","guitar","chelsea","black","diamond","nascar","jackson","cameron","654321","computer","amanda","wizard","xxxxxxxx","money","phoenix","mickey","bailey","knight","iceman","tigers","purple","andrea","horny","dakota","aaaaaa","player","sunshine","morgan","starwars","boomer","cowboys","edward","charles","girls","booboo","coffee","xxxxxx","bulldog","ncc1701","rabbit","peanut","john","johnny","gandalf","spanky","winter","brandy","compaq","carlos","tennis","james","mike","brandon","fender","anthony","blowme","ferrari","cookie","chicken","maverick","chicago","joseph","diablo","sexsex","hardcore","666666","willie","welcome","chris","panther","yamaha","justin","banana","driver","marine","angels","fishing","david","maddog","hooters","wilson","butthead","dennis","captain","bigdick","chester","smokey","xavier","steven","viking","snoopy","blue","eagles","winner","samantha","house","miller","flower","jack","firebird","butter","united","turtle","steelers","tiffany","zxcvbn","tomcat","golf","bond007","bear","tiger","doctor","gateway","gators","angel","junior","thx1138","porno","badboy","debbie","spider","melissa","booger","1212","flyers","fish","porn","matrix","teens","scooby","jason","walter","cumshot","boston","braves","yankee","lover","barney","victor","tucker","princess","mercedes","5150","doggie","zzzzzz","gunner","horney","bubba","2112","fred","johnson","xxxxx","tits","member","boobs","donald","bigdaddy","bronco","penis","voyager","rangers","birdie","trouble","white","topgun","bigtits","bitches","green","super","qazwsx","magic","lakers","rachel","slayer","scott","2222","asdf","video","london","7777","marlboro","srinivas","internet","action","carter","jasper","monster","teresa","jeremy","11111111","bill","crystal","peter","pussies","cock","beer","rocket","theman","oliver","prince","beach","amateur","7777777","muffin","redsox","star","testing","shannon","murphy","frank","hannah","dave","eagle1","11111","mother","nathan","raiders","steve","forever","angela","viper","ou812","jake","lovers","suckit","gregory","buddy","whatever","young","nicholas","lucky","helpme","jackie","monica","midnight","college","baby","brian","mark","startrek","sierra","leather","232323","4444","beavis","bigcock","happy","sophie","ladies","naughty","giants","booty","blonde","golden","0","fire","sandra","pookie","packers","einstein","dolphins","0","chevy","winston","warrior","sammy","slut","8675309","zxcvbnm","nipples","power","victoria","asdfgh","vagina","toyota","travis","hotdog","paris","rock","xxxx","extreme","redskins","erotic","dirty","ford","freddy","arsenal","access14","wolf","nipple","iloveyou","alex","florida","eric","legend","movie","success","rosebud","jaguar","great","cool","cooper","1313","scorpio","mountain","madison","987654","brazil","lauren","japan","naked","squirt","stars","apple","alexis","aaaa","bonnie","peaches","jasmine","kevin","matt","qwertyui","danielle","beaver","4321","4128","runner","swimming","dolphin","gordon","casper","stupid","shit","saturn","gemini","apples","august","3333","canada","blazer","cumming","hunting","kitty","rainbow","112233","arthur","cream","calvin","shaved","surfer","samson","kelly","paul","mine","king","racing","5555","eagle","hentai","newyork","little","redwings","smith","sticky","cocacola","animal","broncos","private","skippy","marvin","blondes","enjoy","girl","apollo","parker","qwert","time","sydney","women","voodoo","magnum","juice","abgrtyu","777777","dreams","maxwell","music","rush2112","russia","scorpion","rebecca","tester","mistress","phantom","billy","6666","albert"); for (var i=0; i < commonPassword.length; i++) { if (commonPassword[i]===commonValue) { return true; } }; return false; }; Before you include it somewhere test it with simple alert: alert(passwordPreventCommon('password')); As the word 'password' is blacklisted it will alert 'true'. Edit: Iteration part can be replaced with includes() method from ES6: if (commonPassword.includes(commonValue)) { return true; }
There is Nist Bad Passwords (NBP) project with a JS library for checking if a password is one of the common used passwords. Check this: https://cry.github.io/nbp/
A slight variation of Ilia Rostovtsev's answer (as I can't post it as a comment). While I'm not saying looping through an array is the fastest way, this is slightly faster due to not checking the array length each time the loop runs, and it also uses ES2015 syntax. const isPasswordCommon = (userPassword) => { const commonPassword = Array("123456","password","12345678","1234","pussy","12345","dragon","qwerty","696969","mustang","letmein","baseball","master","michael","football","shadow","monkey","abc123","pass","6969","jordan","harley","ranger","iwantu","jennifer","hunter","2000","test","batman","trustno1","thomas","tigger","robert","access","love","buster","1234567","soccer","hockey","killer","george","sexy","andrew","charlie","superman","asshole","dallas","jessica","panties","pepper","1111","austin","william","daniel","golfer","summer","heather","hammer","yankees","joshua","maggie","biteme","enter","ashley","thunder","cowboy","silver","richard","orange","merlin","michelle","corvette","bigdog","cheese","matthew","121212","patrick","martin","freedom","ginger","blowjob","nicole","sparky","yellow","camaro","secret","dick","falcon","taylor","111111","131313","123123","bitch","hello","scooter","please","","porsche","guitar","chelsea","black","diamond","nascar","jackson","cameron","654321","computer","amanda","wizard","xxxxxxxx","money","phoenix","mickey","bailey","knight","iceman","tigers","purple","andrea","horny","dakota","aaaaaa","player","sunshine","morgan","starwars","boomer","cowboys","edward","charles","girls","booboo","coffee","xxxxxx","bulldog","ncc1701","rabbit","peanut","john","johnny","gandalf","spanky","winter","brandy","compaq","carlos","tennis","james","mike","brandon","fender","anthony","blowme","ferrari","cookie","chicken","maverick","chicago","joseph","diablo","sexsex","hardcore","666666","willie","welcome","chris","panther","yamaha","justin","banana","driver","marine","angels","fishing","david","maddog","hooters","wilson","butthead","dennis","captain","bigdick","chester","smokey","xavier","steven","viking","snoopy","blue","eagles","winner","samantha","house","miller","flower","jack","firebird","butter","united","turtle","steelers","tiffany","zxcvbn","tomcat","golf","bond007","bear","tiger","doctor","gateway","gators","angel","junior","thx1138","porno","badboy","debbie","spider","melissa","booger","1212","flyers","fish","porn","matrix","teens","scooby","jason","walter","cumshot","boston","braves","yankee","lover","barney","victor","tucker","princess","mercedes","5150","doggie","zzzzzz","gunner","horney","bubba","2112","fred","johnson","xxxxx","tits","member","boobs","donald","bigdaddy","bronco","penis","voyager","rangers","birdie","trouble","white","topgun","bigtits","bitches","green","super","qazwsx","magic","lakers","rachel","slayer","scott","2222","asdf","video","london","7777","marlboro","srinivas","internet","action","carter","jasper","monster","teresa","jeremy","11111111","bill","crystal","peter","pussies","cock","beer","rocket","theman","oliver","prince","beach","amateur","7777777","muffin","redsox","star","testing","shannon","murphy","frank","hannah","dave","eagle1","11111","mother","nathan","raiders","steve","forever","angela","viper","ou812","jake","lovers","suckit","gregory","buddy","whatever","young","nicholas","lucky","helpme","jackie","monica","midnight","college","baby","brian","mark","startrek","sierra","leather","232323","4444","beavis","bigcock","happy","sophie","ladies","naughty","giants","booty","blonde","golden","0","fire","sandra","pookie","packers","einstein","dolphins","0","chevy","winston","warrior","sammy","slut","8675309","zxcvbnm","nipples","power","victoria","asdfgh","vagina","toyota","travis","hotdog","paris","rock","xxxx","extreme","redskins","erotic","dirty","ford","freddy","arsenal","access14","wolf","nipple","iloveyou","alex","florida","eric","legend","movie","success","rosebud","jaguar","great","cool","cooper","1313","scorpio","mountain","madison","987654","brazil","lauren","japan","naked","squirt","stars","apple","alexis","aaaa","bonnie","peaches","jasmine","kevin","matt","qwertyui","danielle","beaver","4321","4128","runner","swimming","dolphin","gordon","casper","stupid","shit","saturn","gemini","apples","august","3333","canada","blazer","cumming","hunting","kitty","rainbow","112233","arthur","cream","calvin","shaved","surfer","samson","kelly","paul","mine","king","racing","5555","eagle","hentai","newyork","little","redwings","smith","sticky","cocacola","animal","broncos","private","skippy","marvin","blondes","enjoy","girl","apollo","parker","qwert","time","sydney","women","voodoo","magnum","juice","abgrtyu","777777","dreams","maxwell","music","rush2112","russia","scorpion","rebecca","tester","mistress","phantom","billy","6666","albert"); const commonPasswordLength = commonPassword.length; for (var i=0; i < commonPasswordLength; i++) { if (commonPassword[i] === userPassword) { return true; } }; return false; }; https://codepen.io/andrethedrummer1/pen/GdobPa
It depends. You can create a text-file with common passwords and check if the password a user entert is in this list. One big drawback is that this file would be very large and it is nearly impossible to cover all common passwords this way. So I would recommend to write a function which checks the user input for different forbidden phrases. For e.g. if you know the real names of the users I would forbid to take them as a part of a password. In addition you can force the user to enter a minimum amount of characters as well as some special characters or numbers.
Exact string match with javascript regex
I'm struggling with what is probably a very simple regex problem. I'm working on a simple prototype and need to know what page I'm on, so I don't reload it if the user clicks a menu widget to navigate to the same view. I have two URLs the user can switch between: http://localhost/TestMVC/Larry/LarryTiles http://localhost/TestMVC/Larry/LarryTilesList The URLs can also have some trailing querystring items, like this: http://localhost/TestMVC/Larry/LarryTilesList?filterValue=servers LarryTiles is giving me the problem. "/\bLarryTiles\b/" worked on Friday (after answers from other questions here) but this doesn't match now. :) I need to find exactly the strings "LarryTiles" and "LarryTilesList" in these two URLs but can't quite figure out how to do that. The URL changes between my local machine and the various servers where it's hosted, so I can't rely on position. EDIT: added the example with a trailing querystring, which I'd forgotten. Sorry :(
You can get the last path segment of an URL like this: function getLastPathSegment(url) { var match = url.match(/\/([^\/]+)\/?$/); if (match) { return(match[1]); } return(""); } // returns "LarryTiles" getLastPathSegment("http://localhost/TestMVC/Larry/LarryTiles"); // returns "LarryTilesList" getLastPathSegment("http://localhost/TestMVC/Larry/LarryTilesList"); So, you could do this: var endPath = getLastPathSegment(window.location.pathname); if (endPath == "LarryTiles") { // some code } else if (endPath == "LarryTilesList") { // some code } else { // some code }
You can use this code: str = 'http://localhost/TestMVC/Larry/LarryTiles?filterValue=servers'; if (str.match(/\/([^\/?]+)(?=\/$|\?|$)/)) { if (match[1] == 'LarryTiles') alert('LarryTiles found'); else if (match[1] == 'LarryTilesList') alert('LarryTilesList found'); }
Seems like what you explained works, otherwise try this: http://jsfiddle.net/Wfz9d/ Do you have a case-sensitivity issue?