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;
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);
}
5条答案
按热度按时间8yoxcaq71#
试试这个:
你也可以使用一个regex和一个replace:
6ie5vjzr2#
你可以使用一个简单的helper函数,比如:
r9f1avp53#
作为替代方案,您可以在空格上拆分字符串,将每个单词大写,然后将它们重新连接在一起:
9lowa7mx4#
Page有一个很好的例子,说明如何在JavaScript中将字符串中的每个单词大写:http://alvinalexander.com/javascript/how-to-capitalize-each-word-javascript-string
9o685dep5#