Trim trailing spaces from variable (not whole file)

Help with writing and running scripts

Trim trailing spaces from variable (not whole file)

Postby ctaylor » Thu Oct 23, 2008 3:45 pm

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");
ctaylor
Newbie
 
Posts: 1
Joined: Thu Oct 23, 2008 3:20 pm

Re: Trim trailing spaces from variable (not whole file)

Postby jorrasdk » Thu Oct 23, 2008 5:56 pm

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();
User avatar
jorrasdk
Master
Master
 
Posts: 275
Joined: Mon Mar 19, 2007 11:00 pm
Location: Denmark


Return to Scripts