Trim and reuse RegExp matches to update string

I have a method to remove the extra spaces between words and trim start and end of strings:

// Remove extra spaces between words and trim start and end of strings
String.prototype.trimmer = function() {
  return String(this).replace(/^\s+|\s+$|\s+(?=\s)/g, '');
};

const text = "    This ,           is!! !not ??trimmed::  :: correctly .   . .      ";

console.log(text.trimmer());

Now the issue is how we can put each of these signs , ! ? : . to be right after the previous word and without any space.

So the desired result for the given text would be:

This, is!!! not?? trimmed:::: correctly...

2 thoughts on “Trim and reuse RegExp matches to update string”

  1. First look for all the signs , ! ? : . (including spaces). Then use those "matches" to replace all spaces and only add one at the end. Not sure if you could achieve the same result with a single Regex. Like so it works.

    String.prototype.trimmer = function() {
      return String(this).replace(
        /([\.\,\!\:\? ]+)/g,
        function(match){
          return match.replace(/ /g, '') + ' ';
        }
      ).trim() // remove spaces at beginning and end of string
    };
    
    const text = "    This ,           is!! !not ??trimmed::  :: correctly .   . .      ";
    
    console.log(text.trimmer());
    Reply
  2. You can also achieve that with a series of regex replaces:

    function trimText(str) {
      return str
      .replace(/\s+([,!?:\.]+)/g, '$1')          // trim leading spaces from punctuation
      .replace(/([,!?:\.])(?![,!?:\.])/g, '$1 ') // add a space after last punctuation
      .replace(/\s\s+/g, ' ')                    // remove excessive spaces
      .trim()                                    // trim leading & trailing spaces
    }
    
    const text = "    This ,           is!! !not ??trimmed::  :: correctly .   . .      ";
    
    console.log('==>' + trimText(text) + '<==');

    Output:

    ==>This, is!!! not?? trimmed:::: correctly...<==
    
    Reply

Leave a Comment