[英]Return First Character of each word in a string
I have a string with Names and I want to convert them to Initials.我有一个带有名称的字符串,我想将它们转换为缩写。 Eg:
例如:
I am looking for a suggesting on how best to do this.我正在寻找有关如何最好地执行此操作的建议。 I have researched using
split()
and looked here http://www.w3schools.com/jsref/jsref_split.asp but could not find a good example of how to target and return first letter when I don't know the char to look for.我研究过使用
split()
并在这里查看http://www.w3schools.com/jsref/jsref_split.asp但是找不到一个很好的例子来说明当我不知道要查找的字符时如何定位和返回第一个字母为了。
My string looks like this我的字符串看起来像这样
<a href="#">John White</a>
and I want to change to this我想改成这个
<a href="#">JW</a>
Any help?有什么帮助吗? Thanks
谢谢
I would suggest you to use RegExp
, Here's an Example我建议你使用
RegExp
,这是一个例子
var myStr = "John P White"; var matches = myStr.match(/\\b(\\w)/g); console.log(matches.join(''));
\\b
assert position at a word boundary (^\\w|\\w$|\\W\\w|\\w\\W)
\\b
在单词边界处断言位置(^\\w|\\w$|\\W\\w|\\w\\W)
1st Capturing Group (
\\w
)第一个捕获组 (
\\w
)
\\w
matches any word character (equal to[a-zA-Z0-9_]
)\\w
匹配任何单词字符(等于[a-zA-Z0-9_]
)Global pattern flags
全局模式标志
g
modifier: global.g
修饰符:全局。 All matches (don't return after first match)所有比赛(第一场比赛后不返回)
var name = "John P White";
function initials(value){
var result = "";
var tokens = value.split(/\s/);
for(var i =0; i < tokens.length; i++){
result += tokens[i].substring(0,1).toUpperCase();
}
return result;
}
initials(name);
You can do:你可以做:
var words = $('a').text().split(' ');
var text = '';
$.each(words, function () {
text += this.substring(0, 1);
});
$('a').text(text);
With delimiter as space
you can split the names and put it into an Array.使用分隔符作为
space
您可以拆分名称并将其放入数组中。 And then you can take the first index of each element inside the Array.然后你可以取数组中每个元素的第一个索引。
You can use a regex to match anything that's not an uppercase letter and then simply remove it.您可以使用正则表达式来匹配不是大写字母的任何内容,然后简单地将其删除。
<a href="#">John White</a>
<a href="#">John P Brown</a>
$('a').each(function(){
var initials = $(this).text().replace(/[^A-Z]/g, "");
$(this).text(initials);
});
Please find below the answer请在下面找到答案
let example_one='John White'; example_one=example_one.split(' ').map(word=>word[0]).join(''); console.log(example_one); let example_two='John P White'; example_two=example_two.split(' ').map(word=>word[0]).join(''); console.log(example_two);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.