首字母大写并删除字符串中的空格

Ric*_*chy -2 javascript regex spaces capitalize

得到一些代码来大写字符串中每个单词的第一个字母.有人可以帮我更新它,这样一旦第一个字母被封顶,它也会删除字符串中的所有空格.

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

jcu*_*bic 6

试试这个:

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;
Run Code Online (Sandbox Code Playgroud)
<div id="output"></div>
Run Code Online (Sandbox Code Playgroud)

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

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;
Run Code Online (Sandbox Code Playgroud)
<div id="output"></div>
Run Code Online (Sandbox Code Playgroud)