Match special characters regex in Javascript (Random place) - javascript

I'm trying to make a regex to match atleast two special characters,
for a password strength checker. I now have this in Javascript:
if (password.match(/([^A-Za-z0-9]{2,})/)) {
//Add strength
}
But this checks that atleast two special characters that needs to be after each other. How can I make it, so that it will also check if it's not after each other?
Example:
_aaa!* //Match
a!a_a* //Also match

One way to do it:
var password = 'a!a_a*';
var matches = password.match(/([^A-Za-z0-9])/g);
if (matches && matches.length >= 2) {
console.log('Good');
} else {
console.log('Bad');
}
console.log(matches);

You could use replace for this:
var password = 'a!a_a*';
var specialChars = password.replace(/[A-Za-z0-9]/g, '');
console.log(password, specialChars.length > 1 ? 'OK' : 'Too few special chars');

^(.*?[\*\& list all the special characters you want to allow here prefixed by \]){2,}.*$
You can test it here: https://regex101.com/

Related

Javascript Regex - replacing characters based on regex rules

I am trying to remove illegal characters from a user input on a browser input field.
const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
console.log('success',myInput)
} else {
console.log("fail",myInput.replace(???, ""))
}
I can test with the right regex and it works just fine. Now I am trying to remove the illegal characters. The rules are, only lower case alpha character in the first position. All remaining positions can only have lower case alpha and numbers 0-9. No spaces or special characters. I am not sure what pattern to use on the replace line.
Thanks for any help you can provide.
Brad
You could try the below code:
const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
console.log('success',myInput)
} else {
console.log("fail",myInput.replace(/[^a-z0-9]/g, ""))
}
Replace is using the following regexp: /[^a-z0-9]/g. This matches all characters that are not lowercase or numeric.
You can validate your regexp and get help from cheatsheet on the following page: https://regexr.com/
You could handle this by first stripping off any leading characters which would cause the input to fail. Then do a second cleanup on the remaining characters:
var inputs = ['abc123', '46432e66Sc'];
inputs.forEach(i => console.log(i + " => " + i.replace(/^[^a-z]+/, "")
.replace(/[^a-z0-9]+/g, "")));
Note that after we have stripped off as many characters as necessary for the input to start with a lowercase, the replacement to remove non lowercase/non digits won't affect that first character, so we can just do a blanket replacement on the entire string.

javascript .match function

I have the following javascript .match script to allow telephone numbers in form submit
var number = jQuery('#phone-number').val();
if ((number.match(/(\d)\1\1\1\1\1/))
|| (number.match(/(\d)(\d)\1\2\1\2\1\2/))
|| (number.match(/123456|234567|345678|456789|567890|987654|876543|765432|654321|543210/))
|| (!number.match(/^(0\d{8,10})?$/))) {
alert("Please supply a valid phone number");
return false;
}
Currently, it doesnt allow a SPACE between numbers.. I'm no good at regex and was wondering if someone could tell me how I allow a SPACE between any number using the script above?
thanks
Craig.
If you want to specify any number of spaces between each character, you can use \s*.
\s stands for whitespace character and * for any number of those
E.g.
\s*(\d)\s*\1\s*\1\s*\1\s*\1\s*\1\s*
const regex = /\s*(\d)\s*\1\s*\1\s*\1\s*\1\s*\1\s*/;
const tel1 = '111111';
const tel2 = ' 1 1 1 1 1 1';
console.log(regex.test(tel1));
console.log(regex.test(tel2));
Ugly, but:
if ((number.match(/(\d)\s*\1\s*\1\s*\1\s*\1\s*\1\s*/))
|| (number.match(/(\d)\s*(\d)\s*\1\s*\2\s*\1\s*\2\s*\1\s*\2\s*/))
|| (number.match(/123456|234567|345678|456789|567890|987654|876543|765432|654321|543210/))
|| (!number.match(/^(0(?:\s*\d\s*){8,10})?$/))) {
alert("Please supply a valid phone number");
return false;
}
For 1 space only replace \s* with \s?
You can remove all spaces from a string with
str = str.replace(/\s/g, '');
Then you can use your existing code.

Extract email address from string

I have a string like this:
Francesco Renga <francesco_renga-001#gmail.com>
I need to extract only the email, i.e. francesco_renga-001#gmail.com.
How can I do this in nodejs/javascript in "elegant" way?
Using regex, if your string pattern is always Some text<email> or Some text<email>, Some text<email> <email> you can use this simple one <(.*?)>
Demo
Other solution
Use positive lookahead : [^<]+(?=>), here is a snippet and a demo
var text = "Francesco Renga <francesco_renga-001#gmail.com>, Marty McFly <mmcfly#gmail.com> Marty McFly <mmcfly#gmail.com> <mmcfly2#gmail.com>";
var re = /[^< ]+(?=>)/g;
text.match(re).forEach(function(email) {
console.log(email);
});
Explanation
[^<]+ match anything but a <between one and unlimited times
(?=>) followed by a >
Simple and does not require any group.
Here's a simple example showing how to use regex in JavaScript :
var string = "Francesco Renga <francesco_renga-001#gmail.com>"; // Your string containing
var regex = /<(.*)>/g; // The actual regex
var matches = regex.exec(string);
console.log(matches[1]);
Here's the decomposition of the regex /<(.*)>/ :
/ and / are mandatory to define a regex
< and > simply matches the two < and > in your string
() parenthesis "capture" what you're looking for. Here, they get the mail address inside.
.* : . means "any character", and * means "any number of times. Combined, it means "any character any number of times", and that is inside < and >, which correspond to the place where the mail is.
Here's a simple code showing how extract the unique list of emails address using JavaScript :
let emaillst = string .match(/([a-zA-Z0-9._+-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
if (emaillst === null) {
// no Email Address Found
} else {
const uniqueEmail = Array.from(new Set(emaillst));
const finaluniqueEmail = [];
for(let i=0; i<=uniqueEmail.length; i++){
let characterIs = String(uniqueEmail[i]).charAt(String(uniqueEmail[i]).length - 1)
if(characterIs==='.'){
finaluniqueEmail.push(String(uniqueEmail[i].slice(0, -1)))
}else{
finaluniqueEmail.push(uniqueEmail[i]);
}
}
emaillst = finaluniqueEmail.join('\n').toLowerCase();
console.log(matches[1]);
See the Live Demo of email address extractor online
Features
Get Unique Emails
Auto remove duplicate emails
convert upper case email address to lowercase

Javascript check for 1 special character and 2 digits

How to create a javascript validation for a password field which must contain at least one special character and at least two digits ?
Exact regular expression that perfect match to your query is below, it is tested ...
^(?=.*?[0-9].*?[0-9])(?=.*[!##$%])[0-9a-zA-Z!##$%]{8,}$
function check(str){
var temp = str;
if(/^[a-zA-Z0-9- ]*$/.test(str) == false && temp.replace(/[^0-9]/g,"").length>1) return true;
return false;
}

Checking for invalid characters from an input with jQuerys

I have an input box where the a username is input'd but if invalid characters are input'd, I want it to error. The code below is what I'm using; What would i put in the "something" section?
var numbers = new RegExp("SOMETHING");
$(this).removeClass("active");
if(($(this).val() == "") || $(this).val().match(numbers))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Here are some patterns I wrote them long years ago:
patt['name'] = /^[a-z ,-]+$/i;
patt['username'] = /^[A-z0-9_-]+$/i;
patt['email'] = /^[a-z0-9]+(?:[\.-]?[a-z0-9]+)*#[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['website'] = /^http(s)?:\/\/(www\.)?[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['age'] = /^(?:([1][3-9]|[2-9][0-9]))$/i;
patt['subject'] = /[a-z0-9?!:;'&_\. ,-]+/i;
If you want to use them, you should check this condition:
if(($(this).val() == "") || ! $(this).val().match(patt['name'])){ // in case.
...
}
But if you want to check undesirable characters, it'll be a long pattern for username input.
Try this Regex
[A-Za-z]
This will match only lowercase and uppercase characters
Suggest you read a bit about regexes and experiment with them.
To get simply letters and nothing else, just do:
^[a-zA-Z]+$
That allows 1..n lowercase & uppercase letters to be found between start and end, nothing else. Sushanth's version will match partial pieces of the input, letting the user to use spaces, numbers, etc. elsewhere as long as there's one piece of of the input with a word in it.
This should be a full implementation of what you're trying to do:
var invalid = /[^A-Za-z]+/;
$(this).removeClass("active");
if($(this).val() == "" || invalid.test($(this).val()))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Sushanth is mostly correct, but you will need to match any number of letters, and it has to be from the start to the end only letters, so you should do something like this
var name = new RegExp('^[A-Za-z]+$');
$(this).removeClass('active');
if($(this).val().match(name)) {
$('#firstNameErrorMsg').html('OK');
} else {
$('#firstNameErrorMsg').html('First name can only contain letters.');
}
If you are looking for validating your users input , to only have letters , i would suggest using the char code, something like this :
add the keypress event on the input tag
for the event args passed, check the character code (Some browsers use keyCode, others use which)
function checkOnKeyDown(event){
if (event.KeyCode >= 65 && event.keyCode <=122)
{
//all ok here -- only upper/lowercase letters accepted
}
else
{
//wrong
}
}
Here is a list with all the keyCode to characters mapping ;) : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Categories

Resources