Reputation: 1688
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:
_username
/ username_
).user_-.name
).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?
Upvotes: 1
Views: 478
Reputation: 13631
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
Upvotes: 1