Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find position of nth token

We have a string that has a maximum limit of 20 words. If the user enters something that is more than 20 words, we then need to truncate the string at its 20th word. How can we automate this? We are able to find the 20th token with #GetToken(myString, 20, ' ')#, but are unsure on how to find it's position in order to left-trim. Any ideas? Thanks in advance.

like image 703
Alex Avatar asked Dec 29 '22 19:12

Alex


2 Answers

The UDF ListLeft() should do what you want. It takes a list and returns the list with the number of elements you define. "Space" is fine as a delimiter.

/**
 * A Left() function for lists.  Returns the n leftmost elements from the specified list.
 * 
 * @param list      List you want to return the n leftmost elements from. 
 * @param numElements      Number of leftmost elements you want returned. 
 * @param delimiter      Delimiter for the list.  Default is the comma. 
 * @return Returns a string, 
 * @author Rob Brooks-Bilson ([email protected]) 
 * @version 1, April 24, 2002 
 */
function ListLeft(list, numElements){
  var tempList="";
  var i=0;
  var delimiter=",";
  if (ArrayLen(arguments) gt 2){
    delimiter = arguments[3];
  }
  if (numElements gte ListLen(list, delimiter)){
    return list;
  }
  for (i=1; i LTE numElements; i=i+1){
    tempList=ListAppend(tempList, ListGetAt(list, i, delimiter), delimiter);
  }
  return tempList;
}

p.s. CFLIB.org is an outstanding resource, and is usually my first stop when I'm looking for something like this. I recommend it highly.

like image 126
ale Avatar answered Jan 12 '23 18:01

ale


Can also use a regular expression (group #1 contains match): ^(?:\w+\s+){19}(\w+)

like image 38
Michael Morton Avatar answered Jan 12 '23 17:01

Michael Morton