Search code examples
javascripthtmlregextextareaentity

How to replace comma + period with period in textarea?


I've created a simple text area where some characters are auto replaced, for example, straight quotes into smart quotes, double dashes to em dash, double spaces to single space.

But now I'm stuck as to how to add script for replacing: (without quotation marks)

word . as word.

word , as word,

word ; as word;

I just want to prevent an extra space before the comma, period, and semicolon and after a word like

Hello world ; should be auto-replaced by Hello world;

Here's my current script:

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

I cannot find an entity to substitute. Does someone happen to have an existing code for this?

if I try

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

or

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

This wouldn't work..


Solution

  • You can use .replace(/\s+(;|,|\.)/, '$1'); to remove all whitespace preceding a semicolon, comma, or period.

    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>