gbvisconti gbvisconti - 6 months ago 12x
Javascript Question

dynamically create user name

I want to create a username based on the name of a person with jquery.

I have no idea how to start, I was thinking about split the name, get the first letter from each part and concatenate with the last name. But I don't know how to do it if the name has lots of words.

For example my name

'First' -> username 'peter'
'First Second' -> username 'fsecond'
'First Second Third' -> username 'fsthird'

code (only do the first case, but what if there are many middle name?)

function createUsername(fullName) {

var piece;
var size;

piece = fullName.split(' ');
size = piece.length;
if(size == 1)

<input type='text' onKeyUp = 'createUsername(this.value)'/>
<input type='text' name='userName' id='userName' />


You can do it like this

function createUsername(name) {
    return name.split(" ").map(function(v, i, a) {
        return i !== (a.length - 1) ? v[0] : v;