【问题标题】:Capitalize first letter and remove space in string大写第一个字母并删除字符串中的空格
【发布时间】:2016-04-23 12:59:15
【问题描述】:

获得了一些代码来将字符串中每个单词的首字母大写。有人可以帮我更新它,以便在第一个字母被加盖后它也会删除字符串中的所有空格。

return function (str) {
    return str.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1);
    });
}

【问题讨论】:

标签: javascript regex spaces capitalize


【解决方案1】:

试试这个:

var input = 'lorem ipsum dolor sit amet';
// \w+ mean at least of one character that build word so it match every
// word and function will be executed for every match
var output = input.replace(/\w+/g, function(txt) {
  // uppercase first letter and add rest unchanged
  return txt.charAt(0).toUpperCase() + txt.substr(1);
}).replace(/\s/g, '');// remove any spaces

document.getElementById('output').innerHTML = output;
<div id="output"></div>

您也可以使用一个正则表达式和一个替换:

var input = 'lorem ipsum dolor sit amet';
// (\w+)(?:\s+|$) mean at least of one character that build word
// followed by any number of spaces `\s+` or end of the string `$`
// capture the word as group and spaces will not create group `?:`
var output = input.replace(/(\w+)(?:\s+|$)/g, function(_, word) {
  // uppercase first letter and add rest unchanged
  return word.charAt(0).toUpperCase() + word.substr(1);
});

document.getElementById('output').innerHTML = output;
<div id="output"></div>

【讨论】:

  • 非常感谢。决定接受这个作为答案,因为它对于寻找这个答案的其他开发人员来说更彻底和理想:)
  • @Richy 好的。享受。但是我之前先给出了完全相同的答案,所以如果你公平地考虑,我唯一没有做的就是提供一个 sn-p。正确的?我会确保从下一个开始这样做。
  • 如果能给出一些解释就好了,特别是正则表达式
  • @KaushikThanki 添加了 cmets
  • 不处理前面的空白。如果需要,在“.replace()”函数之前添加“.trim()”。
【解决方案2】:

您可以使用简单的辅助函数,例如:

return function (str) {
    return str.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1);
    }).replace(/\s/g, "");
}

【讨论】:

    【解决方案3】:

    作为替代方案,您可以在空格上拆分字符串,将每个单词大写,然后将它们重新组合在一起:

    "pascal case".split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1) ).join('')
    

    【讨论】:

      【解决方案4】:

      页面有一个很好的例子,说明如何在 JavaScript 中将字符串中的每个单词大写:http://alvinalexander.com/javascript/how-to-capitalize-each-word-javascript-string

      【讨论】:

        猜你喜欢
        • 2023-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-16
        • 1970-01-01
        • 2015-07-24
        • 1970-01-01
        相关资源
        最近更新 更多