我在jquery中有问题。我想在输入字段中将每个单词的首字母大写。
mycode:
function capitalize(){
console.log($('#alertmsg').val().trim());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<label for="alertmsg"><b>Alert Message</b></label>
<input type="text" name="alertmsg" id="alertmsg" >
<button onClick="capitalize()"> click </button>
jquery
console.log($('#alertmsg').val().trim()); //Hello world
我该怎么办..有人帮助我吗?
简单的正则表达式替换将带您到那里:
const titleCase = (s) => s.replace(/\b\w/g, c => c.toUpperCase());
console.log(titleCase('hello world'));
您应该尝试以下方法:
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
// You do not need to check if i is larger than splitStr length, as your for does that for you
// Assign it back to the array
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
// Directly return the joined string
return splitStr.join(' ');
}
然后
console.log(titleCase("hello world")); //Hello World