获取字符串中单词的第一个字母,并保持其他字母相同

时间:2016-07-13 14:57:21

标签: javascript web

我之前从未真正做过javascript。我正在尝试格式化名称(例如 John Doe 应显示为 J。Doe )。我已经编写了代码来从cookie中获取全名,但我不知道如何格式化它。

这是我现在的代码;它只显示全名:

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);
    }
}

有人可以帮帮我吗?感谢。

3 个答案:

答案 0 :(得分:1)

我推断name_value看起来像是&#34; name = John Doe&#34;。如果是这样的话,你可以这样做:

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];

答案 1 :(得分:0)

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"

答案 2 :(得分:0)

根据您提供的代码

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);
    }
}