我想将每个句子的第一个字母大写,而不是用修改后的textarea值替换,但我认为我的代码中存在一些问题。
$( ".question" ).blur(function() {
var question = $(this).val().match( /[^\.!\?]+[\.!\?]+/g );
question.forEach(function(entry) {
entry = entry.substring(0,1).toUpperCase() + entry.substring(1);
$('.question').val(entry)
});
});
答案 0 :(得分:0)
尝试此功能
function capitalizeSentences(capText, capLock)
{
if (capLock == 1 || capLock == true)
{
capText = capText.toLowerCase();
}
capText = capText.replace(/.n/g, ".[-<br>-]. ");
capText = capText.replace(/.sn/g, ". [-<br>-]. ");
var wordSplit = '. ';
var wordArray = capText.split(wordSplit);
var numWords = wordArray.length;
for(x = 0; x < numWords; x++)
{
wordArray[x] = wordArray[x].replace(wordArray[x].charAt(0), wordArray[x].charAt(0).toUpperCase());
if (x == 0)
{
capText = wordArray[x] + ". ";
}
else if(x != numWords - 1)
{
capText = capText + wordArray[x] + ". ";
}
else if(x == numWords - 1)
{
capText = capText + wordArray[x];
}
}
capText = capText.replace(/[-<br>-].s/g, "n");
capText = capText.replace(/sis/g, " I ");
return capText;
}
以这种方式调用它:
var txt = $('textarea#thetextfieldID').val();
txt = capitalizeSentences(txt, true);
$('textarea#thetextfieldID').val(txt);
答案 1 :(得分:0)
我创建了一个JSfiddle来演示工作代码,但它的要点是你一次只替换一个值,而不是用textarea的全部内容创建一个大值。
这是有效的javascript:
$( ".question" ).blur(function() {
var question = $(this).val().match( /[^\.!\?]+[\.!\?]+/g );
var out = '';
question.forEach(function(entry) {
entry = entry.trim();
entry = entry.substring(0,1).toUpperCase() + entry.substring(1);
out += entry + ' ';
});
$('.question').val(out.trim());
});