Giedrius
Giedrius

Reputation: 1688

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:

  1. Only contains alphanumeric characters, underscore, dash and dot.
  2. Underscore, dash and dot can't be at the end or start of a username (e.g _username / username_).
  3. Underscore, dash and dot can't be next to each other (e.g user_-.name).
  4. 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?

Upvotes: 1

Views: 478

Answers (1)

MikeM
MikeM

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

Related Questions