拆分单词的第一个字符

Splitting the first character of the words

本文关键字:字符 第一个 单词 拆分      更新时间:2023-09-26

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

我试过sbstr(0,2),但这需要JO,有什么办法可以像上面那样形成吗。

使用splitmap:

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

使用正则表达式:

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

要推广@katspaugh给出的regex答案,无论第一个字母是否大写,这都适用于任何字数的所有字符串。

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

将导致JCW

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

旁注

使用这种方法,像John McCooper这样的东西将导致JM而不是JMC

您可以在web上找到一些开箱即用的好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这个名字来区分名字和姓氏。

[来源]

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

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

//如果你确定那就是的名字

此致:(

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

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

这里有一个正则表达式解决方案,它支持像à这样的重音字母和像希伯来语这样的非拉丁语言,并且不假设名称是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>