Get the length of textselection

Photoshop Script Snippets - Note: Full Scripts go in the Photoshop Scripts Forum

Moderators: xbytor, DavideBarranca, Paul MR

Dido_BG

Get the length of textselection

Postby Dido_BG » Sat Apr 07, 2012 7:46 am

The textselection can be usefull in some cases but its not easy to work with it.
Here is a way to get the length.

Code: Select all
function txtSelectionLength (){
      
   // The textselection can be edit only in time of assignment
   w.et.textselection = w.et.textselection.replace( /\n*.+\n*/g,
   
      // Instead of string the second argument can be anonymous function with n number of arguments
      // The first argument (a in this case) is the entire match
      // The following arguments will be the backreferences (characters enclosed with parentheses) used in the regular expression
      // In this case we need the entire textselection so there is no need of backreferences  //
      function(a){ //<F1
   
         // Assign the length in global variable //
         len = a.length
         
         // Return the entire match so there will be no change in the textselection //
         return a;
         
      }
      
   )
      
}

var txt = "12345";

var w = new Window ('dialog', "Test");
   w.et = w.add ('edittext', undefined, txt,{multiline:true});
   w.et.preferredSize = [350,150];
   
   // Create a button that will call the textselection function //
   w.bt = w.add ('button', undefined, "Length")
   
   w.onShow = function (){
   
      // Because the texselection is bugged it needs to be called once when its length is 0 or it will erase the selected text
      txtSelectionLength ()
      
   }
   
   w.bt.onClick = function (){
   
      // For some reason the selection have to be assigned twice to give the proper result
      txtSelectionLength ()
      txtSelectionLength ()
      
      alert ("Length is: " + len)
      
   }
   
   w.show ()
   w.center ()

Return to “Photoshop Scripting: Code Snippets”

Who is online

Users browsing this forum: No registered users and 1 guest