问题描述
我有一个textarea,我希望每个句子中的每个首字母大写。
I have a textarea, where I want every first letter in each sentence to be capitalized.
现在我有这个:
evt.target.value = evt.target.value.replace(/.+?[\.\?\!](\s|$)/g, function(a) {
return a.charAt(0).toUpperCase() + a.slice(1);
});
这是af函数,其中 evt.target
是textarea,函数在keyup上调用。
And this goes in af function, where evt.target
is the textarea, and the function is called on keyup.
它很好用,除了它没有立即大写。
如果我写:
It works great, except that it doesn't capitalize instantly.If I write:
然后只有当我在这个结尾处放置一个句点时,I才会大写。如果它出现在。> whitespace<之后,我希望它在输入后立即大写I。或!> whitespace<或者?> whitespace<。
then the "I" will capitalize only when i put a period at the end of "this". I would like it to capitalize the "I" instantly after typing it, if it comes after an ". >whitespace<" or "! >whitespace<" or "? >whitespace<".
我尝试使用谷歌搜索很多东西,但不幸的是,这个正则表达式的东西对我来说太复杂了。有没有人可以正确地写这个,快速解释一下?
I tried googling a lot of stuff, but unfortunately, this regex stuff is too complicated for me. Could anyone write this correctly, with a quick explanation?
推荐答案
我迟到了,但也许有人需要jQuery代码。
也适用于第一句话。
I'm late, but maybe somebody needs jQuery code for it.That works for first sentence too.
$('input').on('input', function (evt) {
var $this = $(evt.target),
re = /(^|[.!?]\s+)([a-z])/g,
val = $this.val().replace(re, function (m, $1, $2) {
return $1 + $2.toUpperCase();
});
$this.val(val);
});
es6 update:
es6 update:
let re = /(^|[.!?]\s+)([a-z])/g;
$('input').on('input', function (evt) {
let $this = $(this),
val = $this.val().replace(re, (m, $1, $2) => $1 + $2.toUpperCase());
$this.val(val);
});
这篇关于如何在JavaScript之后大写首字母,问号和感叹号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!