【问题标题】:How to get character after space in JavaScript如何在javascript中的空格后获取字符
【发布时间】:2023-04-03 13:54:01
【问题描述】:

我正在处理 Avatar 组件,我想在其中获取第一个字符和空格后的字符并将结果提供给化身并显示全名的缩写版本,例如:-

var fullName = ahmed hosny;

//I am able to get the first character like this:- 

fullName.charAt(0).toUpperCase() // this prints 'A'

我的问题是如何从 hosny 获得“H”?谢谢

【问题讨论】:

    标签: javascript


    【解决方案1】:

    为此使用正则表达式。

    首次出现

    console.log(fullName.match(/(?<= )./))
    // returns [ 'h', index: 6, input: 'ahmed hosny', groups: undefined ]
    

    所有情况

    console.log(fullName.match(/(?<= )./g))
    // returns array of all characters after space
    

    【讨论】:

    • 让我看看我只想要第一次出现的空格,因为我希望头像只包含两个字符
    • 他们应该使用第一个选项
    • 感谢兄弟它的工作有什么办法可以将结果转换为大写?
    • 当然,字符串后面的 .toUpperCase() 就可以了
    • 之前试过了,没用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2017-05-06
    • 2020-11-10
    相关资源
    最近更新 更多