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

llycmphe  于 2023-06-25  发布在  其他
关注(0)|答案(5)|浏览(146)

得到了一些代码来大写字符串中每个单词的第一个字母。有人能帮我更新它,以便它也删除字符串内的所有空格,一旦第一个字母是大写的。

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

8yoxcaq71#

试试这个:

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>

你也可以使用一个regex和一个replace:

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>
6ie5vjzr

6ie5vjzr2#

你可以使用一个简单的helper函数,比如:

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

r9f1avp53#

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

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

9lowa7mx4#

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

9o685dep

9o685dep5#

function wordSearch()
{
   var paragraph=document.getElementById("words").value;
   let para2=paragraph.replace(/\s+/g,'');//remove whitespaces
   let para3=para2.charAt(0).toUpperCase()+para2.slice(1); 
   //uppercase first letter
   alert(para3);
 }

相关问题