regexp - first and last name javaScript - javascript

I'm trying to make a JavaScript regexp such as the facebook uses for real names:
Names can’t include:
Symbols
numbers
unusual capitalization
repeating characters or punctuation
source: Facebook help center
Here is my regexp:
/^[a-z \,\.\'\-]+$/i
The problem with this regexp is that it doesn't check for repeated characters or punctuation:
then I found this :
/(.)\1/
so I'm now checking it like this:
$('input [type=text]).keyup(function(){
var name = $(this).val();
var myregex = /^[a-z\,\.\'\-]+$/i
var duplicate = /(.)\1/
if(name != myregex.exec(name) || name == /(.)\1/)
{// the name entered is wrong
}
else
//the name is ok
but the problem I'm facing is with inputs like:
Moore
Callie
Maggie
what can I do to get the problem solved?

You should stop trying to solve this problem:
It is very complicated
Names are very personal
For instance your system will never be able to validate names from China
or Japan.... (For instance: Børre Ørevål ,汉/漢 )
So just leave the whole idea, and let people freely enter their names with no restrictions.
Related: Regular expression for validating names and surnames?

Related

regex email pattern in a negate way

I was working around some regex pattern
I have a variable,
var url = "last_name=Ahuja&something#test.com";
The url contains emailId. I have a regex pattern to check if the variable contains emailId.
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
My requirement is:
I want exact negate(opposite) of the above pattern. Like, My condition should be false if the url contains email pattern.
I mean the regex pattern should be in that way.
Can somebody please help me on this.
Instead of negating your regex, you can test whether it matches.
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var url = "last_name=Ahuja&something#test.com";
if(-1 === url.search(filter))
{
alert("Didn't find it");
}
else
{
alert("Found it");
}
Using a negative lookahead you can check if the string does not have an email at the beginning, which mimics the behavior you want since your regex had start and end anchors.
^(?!([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+).*$
But if you wanted to make sure there was no valid email anywhere in the line, you could modify this a little.
^((?!([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+).)*$
See an explanation here
But you should just do this in code like Jonathan suggests.

how to split list of emails with javascript split

I am having trouble with javascript split method. I would like some code to 'split' up a list of emails.
example: test#test.comfish#fish.comnone#none.com
how do you split that up?
Regardless of programming language, you will need to write (create) artificial intelligence which will recognize emails (since there is no pattern).
But since you are asking how to do it, I assume that you need really simple solution. In that case split text based on .com, .net, .org ...
This is easy to do, but it will generate probably a lot of invalid emails.
UPDATE: Here is code example for simple solution (please note that this will work only for all domains that end with 3 letter like: .com, .net, .org, .biz...):
var emails = "test#test.comfish#fish.comnone#none.com"
var emailsArray = new Array()
while (emails !== '')
{
//ensures that dot is searched after # symbol (so it can find this email as well: test.test#test.com)
//adding 4 characters makes up for dot + TLD ('.com'.length === 4)
var endOfEmail = emails.indexOf('.', emails.indexOf('#')) + 4
var tmpEmail = emails.substring(0, endOfEmail)
emails = emails.substring(endOfEmail)
emailsArray.push(tmpEmail)
}
alert(emailsArray)
This code has downsides of course:
It won't work for other then 3-char's TLS's
It won't work if domain has subdomain, like test#test.test.com
But I believe that it has best time_to_do_it/percent_of_valid_emails ratio due to very very little time needed to make it.
Assuming you have different domains, like .com, .net etc and can't just split on .com, AND assuming your domain names and recipient names are the same like in each of your three examples, you might be able to do something crazy like this:
var emails = "test#test.comfish#fish.comnone#none.com"
// get the string between # and . to get the domain name
var domain = emails.substring(emails.lastIndexOf("#")+1,emails.lastIndexOf("."));
// split the string on the index before "domain#"
var last_email = split_on(emails, emails.indexOf( domain + "#" ) );
function split_on(value, index) {
return value.substring(0, index) + "," + value.substring(index);
}
// this gives the first emails together and splits "none#none.com"
// I'd loop through repeating this sort of process but moving in the
// index of the length of the email, so that you split the inner emails too
alert(last_email);
>>> test#test.comfish#fish.com, none#none.com

Regex expression to match the First url after a space followed

I want to match the First url followed by a space using regex expression while typing in the input box.
For example :
if I type www.google.com it should be matched only after a space followed by the url
ie www.google.com<SPACE>
Code
$(".site").keyup(function()
{
var site=$(this).val();
var exp = /^http(s?):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
var find = site.match(exp);
var url = find? find[0] : null;
if (url === null){
var exp = /[-\w]+(\.[a-z]{2,})+(\S+)?(\/|\/[\w#!:.?+=&%#!\-\/])?/g;
var find = site.match(exp);
url = find? 'http://'+find[0] : null;
}
});
Fiddle
Please help, Thanks in advance
you should be using a better regex to correctly match the query & fragment parts of your url. Have a look here (What is the best regular expression to check if a string is a valid URL?) for a correct IRI/URI structured Regex test.
But here's a rudimentary version:
var regex = /[-\w]+(\.[a-z]{2,})+(\/?)([^\s]+)/g;
var text = 'test google.com/?q=foo basdasd www.url.com/test?q=asdasd#cheese something else';
console.log(text.match(regex));
Expected Result:
["google.com/?q=foo", "www.url.com/test?q=asdasd#cheese"]
If you really want to check for URLs, make sure you include scheme, port, username & password checks just to be safe.
In the context of what you're trying to achieve, you should really put in some delay so that you don't impact browser performance. Regex tests can be expensive when you use complex rules especially so when running the same rule every time a new character is entered. Just think about what you're trying to achieve and whether or not there's a better solution to get there.
With a lookahead:
var exp = /[-\w]+(\.[a-z]{2,})+(\S+)?(\/|\/[\w#!:.?+=&%#!\-\/])?(?= )/g;
I only added this "(?= )" to your regex.
Fiddle

Javascript Validation - Letters and Space

Good day. I'm very new to Javascript. I have this expression: var firstname = /^[A-Za-z]+$/; to validate first name in a form. However, this code only allows the user to input a single name without any space. How about if the user has two or more given first name?
I would like to know how to validate letters and space. I have searched similar questions here in Stackoverflow, but none of the answers worked for me.
I have tried these codes which I have found here: /^[A-Za-z ]$/ or this one /^[a-zA-Z\s]*$/ but these didn't work. Still, whenever I input two names in the First Name field, my alert message prompts me that I have entered an invalid character.
Thanks.
There is a problem with each one that you posted for what you want:
var firstname = /^[A-Za-z]+$/; should be var firstname = /^[A-Za-z ]+$/; (added space)
/^[A-Za-z ]$/ should be /^[A-Za-z ]+$/ (added +)
/^[a-zA-Z\s]*$/ is a problem because I assume from the other examples that you want at least one letter, so it should be /^[a-zA-Z\s]+$/ (*replaced * with +)

Extract proper username from a string with regex in js

I want to extract a username from a string that user has typed into input. The thing is that I don't want just simply validate username, but I want to show for user what will be the final username even if user types any non-allowed characters.
So for example if user types in something like &%$User)(Nam-e it will show usernam-e
there is similar question with answer Regular expression to validate username, but somehow it gives me an error of Invalid group on node.js when I try to use it with a match or exec functions.
Anyway, most of the examples online only validates the username against regex, but not actually provides the outcome of the appropriate username.
Rules are following:
Only contains alphanumeric characters, underscore, dash and dot.
Underscore, dash and dot can't be at the end or start of a username
(e.g _username / username_).
Underscore, dash and dot can't be next to each other (e.g
user_-.name).
Underscore, dash or dot can't be used multiple times in a row (e.g
user__name).
So far I was only capable to do something similar with using replace function number of times
value.replace(/[^\w-]*/g,'').replace(/^[^a-z]*/,'').replace(/-{2,}/g,'-').replace(/_{2,}/g,'_');
But this doesn't look like an efficient code, especially that I would actually need to add even more replace functions to extract appropriate username.
Any ideas how to achieve that?
Assumes that you want the name displayed in lower-case, as in your example:
function user( n ) {
var name = n.replace( /^[^a-z]+|[^a-z\d_\-.]|[_\-.](?![a-z\d])/gi, '' );
if ( n != name ) {
console.log( 'Username invalid' );
}
return name.toLowerCase();
}
user('&%$User)(Nam-e'); // Username invalid, usernam-e
user('_Giedrius_one_'); // Username invalid, giedrius_one
user('Giedrius--one'); // Username invalid, giedrius-one
user('Giedrius-one'); // giedrius-one
user('/.bob_/'); // Username invalid, bob

Categories

Resources