Tapatalk

Trim trailing spaces from variable (not whole file)

Trim trailing spaces from variable (not whole file)

1
NewbieNewbie
1

    Oct 23, 2008#1

    I have a variable length, space delimited string (variable name "avg_period") that has trailing spaces that I need to remove before using the "split" command in a script. I could not find a clean way to do this other than trimming the trailing spaces from the whole file (rather than just the string I need). Is there a method to trim spaces from a variable?
    Alternatively, I wanted to define a delimiter to "split" the string such as a non-whitespace character followed by a space but was not successful.
    Any suggestions? Here is my code:

    Code: Select all

    var delim = " ";
      //Define Array to contain the averaging periods processed for each output file
        var stringArray = new Array(); //create array to hold all processed averaging periods
        var arrayLength = 0; //array length
        var avg_period; //variable which holds selection
      
      //Get averaging periods
        UltraEdit.document[index].findReplace.find("AVERTIME");//Keyword for listing the averaging periods
        if (UltraEdit.document[index].isFound() == true) {
          UltraEdit.document[index].gotoLine(0,13);
          UltraEdit.document[index].gotoLineSelect(0,50);
          avg_period = UltraEdit.document[index].selection;
        }
        //split string at "delim"	
        stringArray = avg_period.split(delim);
        
        //get number of averaging periods processed
        arrayLength = stringArray.length;
        UltraEdit.activeDocument.write(arrayLength + "\r\n");
    

    262
    MasterMaster
    262

      Oct 23, 2008#2

      If you google for words like "javascript prototype string" you will get links for all sorts of useful javascript prototype extensions for the String object.

      Some of them will be variations on the "trim theme". Example:

      String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };

      This adds a trim() function to the javascript String object that using a regular expression removes leading and trailing whitespace. This way you can use trim() all over your script on any variable that is a String.

      If you add this prototype declaration in the start of your script, you can change the line where you retrieve the selection to:

      avg_period = UltraEdit.document[index].selection.trim();