拆分单词的第一个字符

时间:2011-11-15 08:49:31

标签: javascript

我有一个要求,我必须单独拿两个单词的第一个字母。就像我从WebService获得John Cooper的响应一样,我必须从中获取JC

我试过了sbstr(0,2),但这需要JO,有没有办法像上面那样形成。

6 个答案:

答案 0 :(得分:34)

splitmap

'John Cooper'.split(' ').map(function (s) { return s.charAt(0); }).join('');

使用regular expressions

'John Cooper'.replace(/[^A-Z]/g, '');

答案 1 :(得分:11)

为了概括@katspaugh给出的正则表达式答案,这将适用于包含任意数量单词的所有字符串,无论第一个字母是否大写。

'John Cooper workz'.replace(/\W*(\w)\w*/g, '$1').toUpperCase()

将导致JCW

显然,如果你想保留每个单词的第一个字母的大小写,只需删除toUpperCase()

SIDE NOTE

使用这种方法,John McCooper之类的内容会导致JM而非JMC

答案 2 :(得分:3)

您可以在网上找到一些开箱即用的优秀JavaScript功能:

function getInitials(x)
{
        //(x is the name, e.g. John Cooper)

        //create a new variable 'seperateWords'
        //which uses the split function (by removing spaces)
        //to create an array of the words
        var seperateWords = x.split(" ");

        //also create a new empty variable called acronym
        //which will eventually store our acronym
        var acronym = "";

        //then run a for loop which runs once for every
        //element in the array 'seperateWords'.
        //The number of elements in this array are ascertained
        //using the 'seperateWords.length' variable
        for (var i = 0; i < seperateWords.length; i++){

            //Eacy letter is added to the acronym
            //by using the substr command to grab
            //the first letter of each word
            acronym = (acronym + seperateWords[i].substr(0,1));
        }

        //At the end, set the value of the field
        //to the (uppercase) acronym variable
        // you can store them in any var or any HTML element
        document.register.username2.value = toUpperCase(acronym);
}

您尝试遗漏的诀窍是先将split名称分隔名字和姓氏。

[Source]

答案 3 :(得分:3)

好吧,如果我让你写,那么只需尝试以下

var words = 'John Cooper'.split(' ');
var shortcut = words[0][0] + words[1][0];
alert(shortcut);

//多数民众赞成,如果你确定这个名字是2个单词

问候:)

答案 4 :(得分:2)

var name = "John Cooper";
var initials = "";
var wordArray = name.split(" ");
for(var i=0;i<wordArray.length;i++)
{
    initials += wordArray[i].substring(0,1);
}
document.write(initials);

基本上你在空格上分割字符串并取出每个单词的第一个字符。

答案 5 :(得分:0)

这是一个正则表达式解决方案,支持像à和非拉丁语言(如希伯来语)的重音字母,并且不会假设名称是Camel-Case:

var name = 'ḟoo Ḃar';
var initials = name.replace(/\s*(\S)\S*/g, '$1').toUpperCase();
document.getElementById('output').innerHTML = initials;
<div id="output"></div>

相关问题