拆分单词的第一个字符
Splitting the first character of the words
我有一个要求,我必须单独取两个单词的第一个字母。就像我从WebService得到的响应是John Cooper
,我必须从中获得JC
。
我试过sbstr(0,2)
,但这需要JO,有什么办法可以像上面那样形成吗。
使用split
和map
:
'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>
相关文章:
- 而循环只设置php中输入字段中的第一个值
- 错误:$injector:modulerr模块错误(我的第一个SPA应用程序)
- IE11中的第二个调用取消了第一个Fetch API调用
- Javascript XMLHttpRequest——只有第一个POST请求有效
- 使用javascript或angularjs特定过滤器搜索字符串中第一个img标记的json值
- 将OnClick函数设置为<ul>,最后一个ul是擦除第一个ul-s
- RxJS油门行为;立即获取第一个值
- Regex-从字符第N次出现到字符串末尾的匹配
- Angular UI网格:如何通过第一个UI网格中的按钮使第二个UI网格可见
- 选择多个实例中的第一个
- 如何在调用下一个请求之前完成第一个Ajax Get请求
- 在跨度中每3个字符添加一个空格
- 如何在JavaScript中每隔第n个字符分割一个字符串
- Lodash:返回对象的第一个键,该对象的值(即数组)中有一个给定的元素(即字符串)
- 看起来第一个console.log是'It’不太对
- 与杜兰达尔合作的第一个JavaScript项目.尝试从第三方 API 获取数据
- 节点发布错误对象的第一个“属性”
- Javascript:表单验证getElementById仅返回第一个id元素
- 删除最后一个无效字符,而不是第一个(javascript验证)
- 获得第一个n个文本字符的网页与他们的风格等