El Dj
El Dj

Reputation: 385

Get first letter of a word in string and keep others the same

I've never really done javascript before. I'm trying to format names (for e.g. John Doe should appear as J. Doe). I have written the code to grab the Full name from a cookie but I don't know how to format it that way.

This is my code right now; it just displays the full name:

var cookieParts = document.cookie.split(";");
var userName = "";
for (var i = 0; i < cookieParts.length; i++) {
    var name_value = cookieParts[i],
    equals_pos = name_value.indexOf("="),
    name       = unescape( name_value.slice(0, equals_pos) ).trim(),
    value      = unescape( name_value.slice(equals_pos + 1) );
    if(name == "fullName"){
        userName = value.substring(0,1);
    }
}

Can someone please help me? Thanks.

Upvotes: 0

Views: 62

Answers (4)

George Pant
George Pant

Reputation: 2117

Based on the code you provided

var cookieParts = document.cookie.split(";");
var userName = "";
for (var i = 0; i < cookieParts.length; i++) {
    var name_value = cookieParts[i],
    equals_pos = name_value.indexOf("="),
    name       = unescape( name_value.slice(0, equals_pos) ).trim(),
    value      = unescape( name_value.slice(equals_pos + 1) );
    if(name == "fullName"){
        userName = value.split(" ");
        userName[0]=userName[0].substring(0,1)+'.';
        userName = userName.join(" ");
        alert(userName);
    }
}

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386624

You could use a regex and replace with the wanted style.

console.log('Doe'.replace(/([A-Z])\w*(?=\s)/g, '$1.'));
console.log('John Doe'.replace(/([A-Z])\w*(?=\s)/g, '$1.'));
console.log('John John Doe'.replace(/([A-Z])\w*(?=\s)/g, '$1.'));

If you want only replace the first occurence, then omit g (global) flag.

console.log('Doe'.replace(/([A-Z])\w*(?=\s)/, '$1.'));
console.log('John Doe'.replace(/([A-Z])\w*(?=\s)/, '$1.'));
console.log('John John Doe'.replace(/([A-Z])\w*(?=\s)/, '$1.'));

Upvotes: 1

andrunix
andrunix

Reputation: 1754

I am inferring that name_value looks something like, "name=John Doe". If that's the case, you could do:

name_parts = name_value.split("=");
first_last = name_parts[1].split(" "); // assumes no spaces other than 1 between first and last name.

first_initial_last = first_last[0].substring(0, 1) + '. ' + first_last[1];

Upvotes: 1

pishpish
pishpish

Reputation: 2614

function formatName( fullName ){

  var names = fullName.split(' ');
  for( var i = 0, n = names.length-1; i < n; i++ )
    names[i] = names[i][0];
  return names.join('. ') ;

}

console.log( formatName("Oscar Fingal O'Flahertie Wills Wilde") );  // "O. F. O. W. Wilde"

Upvotes: 0

Related Questions