在Javascript中获取字符串中每个单词的第一个字母 [英] Get first letter of each word in a string, in Javascript

查看:163
本文介绍了在Javascript中获取字符串中每个单词的第一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何收集字符串中每个单词的第一个字母,如收到缩写?

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"


推荐答案

我认为你所寻找的是所提供字符串的首字母缩写。

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)

注意: 这对于带连字符/撇号的单词会失败帮帮我 - 我死了将是 HmImD 。如果这不是你想要的,那么分割空间,抓住第一个字母方法可能就是你想要的。

Note: this will fail for hyphenated/apostrophe'd words Help-me I'm Dieing will be HmImD. If that's not what you want, the split on space, grab first letter approach might be what you want.

这是一个快速的例子:

let str = "Java Script Object Notation";
let acronym = str.split(/\s/).reduce((response,word)=> response+=word.slice(0,1),'')

console.log(acronym);

这篇关于在Javascript中获取字符串中每个单词的第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆