如何在JavaScript之后大写首字母,问号和感叹号? [英] How to capitalize first letter after period, question mark and exclamation in JavaScript?

查看:136
本文介绍了如何在JavaScript之后大写首字母,问号和感叹号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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:


嘿。我需要一些正则表达式。

Hey. i need some regular expression for this.

然后只有当我在这个结尾处放置一个句点时,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);
});

https://jsfiddle.net/chukanov/oqg5o88u/1/

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);
});

https://jsfiddle.net/chukanov/oqg5o88u/27/

这篇关于如何在JavaScript之后大写首字母,问号和感叹号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆