2011-11-15 109 views
15

我有一个要求,我必须单独带两个单词的第一个字母。就像我从WebService得到的回应为John Cooper,我必须从这里取JC分割单词的第一个字符

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

回答

34

随着splitmap

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

随着regular expressions

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

真的爱它正则表达式:) nice work +1 – Marwan

+1

这个正则表达式假设每个单词都以大写字母开头。其他答案有更好的正则表达式。 – Groady

+0

@Groady错了。这个正则表达式只是用空字符串替换任何小写字母。在这种情况下插入字符'^'的意思是“不”(所以括号中的组与大写字母都不匹配)。 – katspaugh

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]

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

基本上你上的空间分割字符串和采取的第一个字符每个字。

+1

['substr'](https://developer.mozilla。org/en/JavaScript/Reference/Global_Objects/String/substr)是非标准的,更好的使用['substring'](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring)或['slice'](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/slice)。 – katspaugh

+0

我不知道 - 已将其更改为'substring()'。 –

3

好吧,如果我给你写了这么简单的请尝试以下

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

//这就是如果你确信这个名字是在2个字

问候:)

11

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

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

将导致JCW

很明显,如果你想保持的第一个字母的情况下,每个字,只是删除toUpperCase()

边注

这种方法,像John McCooper会导致JM而不是JMC

0

下面是支持重音字母像和非拉丁语系语言,如希伯来语正则表达式的解决方案,并且不承担名字是骆驼案例:

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

相关问题