【问题标题】:How to replace comma + period with period in textarea?如何在textarea中用句点替换逗号+句点?
【发布时间】:2020-08-14 02:10:57
【问题描述】:

我创建了一个简单的文本区域,其中一些字符会自动替换,例如,将直引号替换为智能引号、将双破折号替换为 em 破折号、将双空格替换为单个空格。

但现在我不知道如何添加替换脚本:(不带引号)

word . as word.

word , as word,

word ; as word;

我只是想防止在逗号、句号和分号之前以及像这样的单词之后出现额外的空格

Hello world ; 应自动替换为 Hello world;

这是我当前的脚本:

    var $message = $("#textarea1");

    $message.on("keydown keypress", function() {    
        var $this = $(this),
            val = $(this).val()
                         .replace(/(^|[-\u2014\s(\["])'/g, "$1\u2018")
                         .replace(/'/g, "\u2019")
                         .replace(/(^|[-\u2014/\[(\u2018\s])"/g, "$1\u201c")
                         .replace(/"/g, "\u201d")
                         .replace(/--/g, "\u2014")
                         .replace(/ +(?= )/g,'');

        $this.val(val);
    });

我找不到可以替代的实体。有人碰巧有这方面的现有代码吗?

如果我尝试

.replace(/ ;/g, "\;")

或

.replace(/ /g, "\;")

这行不通..

【问题讨论】:

  • 你要试试.replace(/ /g, ";") 或.replace(/ /gi, ";") 吗?

标签: javascript html regex textarea entity


【解决方案1】:

您可以使用.replace(/\s+(;|,|\.)/, '$1'); 删除分号、逗号或句点之前的所有空格。

var $message = $("#textarea1");

$message.on("keydown keypress", function() {    
  var $this = $(this),
      val = $(this).val()
  .replace(/(^|[-\u2014\s(\["])'/g, "$1\u2018")
  .replace(/'/g, "\u2019")
  .replace(/(^|[-\u2014/\[(\u2018\s])"/g, "$1\u201c")
  .replace(/"/g, "\u201d")
  .replace(/--/g, "\u2014")
  .replace(/ +(?= )/g,'')
  .replace(/\s+(;|,|\.)/, '$1');

  $this.val(val);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="textarea1"></textarea>

【讨论】:

  • 我可以跟进一下,分号和逗号工作正常,但句号不正常。它正在删除所有空格并连接所有单词。周期实体还有其他选择吗?
  • 我的错;我忘记转义了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-14
  • 2016-09-29
  • 2018-05-31
  • 2016-10-30
  • 2020-07-24
  • 2016-09-05
  • 2018-07-06
相关资源
最近更新 更多