Javascript 在Javascript中获取字符串中每个单词的第一个字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8279859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get first letter of each word in a string, in Javascript
提问by Gerben Jacobs
How would you go around to collect the first letter of each word in a string, as in to receive an abbreviation?
您将如何收集字符串中每个单词的第一个字母,例如接收缩写?
String: "Java Script Object Notation"
Wanted result: "JSON"
回答by BotNet
I think what you're looking for is the acronym of a supplied string.
我认为您正在寻找的是所提供字符串的首字母缩写词。
var str = "Java Script Object Notation";
var matches = str.match(/\b(\w)/g); // ['J','S','O','N']
var acronym = matches.join(''); // JSON
console.log(acronym)
Note:this will fail for hyphenated/apostrophe'd words Help-me I'm Dieingwill be HmImD. If that's not what you want, the split on space, grab first letterapproach might be what you want.
注:这将失败的连字符/ apostrophe'd话Help-me I'm Dieing会HmImD。如果这不是你想要的,空间分割,抓住第一个字母的方法可能是你想要的。
Here's a quick example of that:
这是一个简单的例子:
let str = "Java Script Object Notation";
let acronym = str.split(/\s/).reduce((response,word)=> response+=word.slice(0,1),'')
console.log(acronym);
回答by hugomg
I think you can do this with
我认为你可以做到这一点
'Aa Bb'.match(/\b\w/g).join('')
Explanation:Obtain all /gthe alphanumeric characters \wthat occur after a non-alphanumeric character (i.e: after a word boundary \b), put them on an array with .match()and join everything in a single string .join('')
说明:获取出现在非字母数字字符之后的所有/g字母\w数字字符(即:在单词边界之后\b),将它们放在一个数组中,.match()并将所有内容连接到一个字符串中.join('')
Depending on what you want to do you can also consider simply selecting all the uppercase characters:
根据您要执行的操作,您还可以考虑简单地选择所有大写字符:
'JavaScript Object Notation'.match(/[A-Z]/g).join('')
回答by Almis
Easiest way without regex
没有正则表达式的最简单方法
var abbr = "Java Script Object Notation".split(' ').map(function(item){return item[0]}).join('');
回答by Aaron Taddiken
This is made very simple with ES6
这在ES6 中变得非常简单
string.split(' ').map(i => i.charAt(0)) //Inherit case of each letter
string.split(' ').map(i => i.charAt(0)).toUpperCase() //Uppercase each letter
string.split(' ').map(i => i.charAt(0)).toLowerCase() //lowercase each letter
This ONLY works with spaces or whatever is defined in the .split(' ')method
这仅适用于空格或.split(' ')方法中定义的任何内容
ie, .split(', ').split('; '), etc..
即.split(', ').split('; '),等等。
回答by tomersss2
@BotNet flaw: i think i solved it after excruciating 3 days of regular expressions tutorials:
@BotNet 缺陷:我想我在折磨了 3 天的正则表达式教程后解决了它:
==> I'm a an animal
==> 我是一只动物
(used to catch m of I'm) because of the word boundary, it seems to work for me that way.
(用于捕捉我的 m)由于词边界,它似乎对我有用。
/(\s|^)([a-z])/gi
回答by Darryl Hebbes
To add to the great examples, you could do it like this in ES6
要添加到很棒的示例中,您可以在 ES6 中这样做
const x = "Java Script Object Notation".split(' ').map(x => x[0]).join('');
console.log(x); // JSON
and this works too but please ignore it, I went a bit nuts here :-)
这也有效,但请忽略它,我在这里有点疯狂:-)
const [j,s,o,n] = "Java Script Object Notation".split(' ').map(x => x[0]);
console.log(`${j}${s}${o}${n}`);
回答by Ben Sarah Golightly
Using map(from functional programming)
使用map(来自函数式编程)
'use strict';
function acronym(words)
{
if (!words) { return ''; }
var first_letter = function(x){ if (x) { return x[0]; } else { return ''; }};
return words.split(' ').map(first_letter).join('');
}
回答by ipr101
Try -
尝试 -
var text = '';
var arr = "Java Script Object Notation".split(' ');
for(i=0;i<arr.length;i++) {
text += arr[i].substr(0,1)
}
alert(text);
Demo - http://jsfiddle.net/r2maQ/
回答by Fatma Nabilla
Alternative 1:
备选方案 1:
you can also use this regex to return an array of the first letter of every word
您还可以使用此正则表达式返回每个单词的第一个字母的数组
/(?<=(\s|^))[a-z]/gi
(?<=(\s|^))is called positive lookbehindwhich make sure the element in our search pattern is preceded by (\s|^).
(?<=(\s|^))被调用positive lookbehind以确保我们搜索模式中的元素以(\s|^).
so, for your case:
所以,对于你的情况:
// in case the input is lowercase & there's a word with apostrophe
const toAbbr = (str) => {
return str.match(/(?<=(\s|^))[a-z]/gi)
.join('')
.toUpperCase();
};
toAbbr("java script object notation"); //result JSON
(by the way, there are also negative lookbehind, positive lookahead, negative lookahead, if you want to learn more)
(顺便说一句,如果你想了解更多,还有negative lookbehind, positive lookahead, negative lookahead)
Alternative 2:
备选方案 2:
match all the words and use replace()method to replace them with the first letter of each word and ignore the space (the method will not mutate your original string)
匹配所有单词并使用replace()方法将它们替换为每个单词的第一个字母并忽略空格(该方法不会改变您的原始字符串)
// in case the input is lowercase & there's a word with apostrophe
const toAbbr = (str) => {
return str.replace(/(\S+)(\s*)/gi, (match, p1, p2) => p1[0].toUpperCase());
};
toAbbr("java script object notation"); //result JSON
// word = not space = \S+ = p1 (p1 is the first pattern)
// space = \s* = p2 (p2 is the second pattern)
回答by Vadim Gremyachev
Yet another option using reducefunction:
使用reduce函数的另一个选项:
var value = "Java Script Object Notation";
var result = value.split(' ').reduce(function(previous, current){
return {v : previous.v + current[0]};
},{v:""});
$("#output").text(result.v);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="output"/>

