SPFE Documentation | Collections > SPFE Function Reference > first-n-words

Function: first-n-words

first-n-words(text as item()*, words as xs:integer, suffix as xs:string) as item()*

Description

Returns that first number of words of a specified string, and optionally adds a specified suffix. For example, calling this function like this:

<xsl:value-of select="sf:first-n-words('The quick brown fox', 3, '...')/>

Will return:

The quick brown ...

This is useful for creating exerpts of a text to appear in a list or to lable a link.

Return value

Return type: item()*

The truncated string with the specified prefix. If there number of words in the string is less than or equal to the number specified in the words parameter, the whole string is returned. The function recognizes words by matching spaces between words. The returned string includes the final space after the late matched world, if one exists in the input string. The suffix is added after this space. If specified, the suffix is always added, even if the whole string is returned.

Source file

$SPFEOT_HOME/1.0/scripts/common/utility-functions.xsl

Parameters

text

Type: item()*

The string to be truncated.

words

Type: xs:integer

The number of words to be returned.

suffix

Type: xs:string

The suffix string to be added to the returned string.

Definition

            <xsl:function name="sf:first-n-words">
		               <xsl:param name="text"/>
		               <xsl:param name="words" as="xs:integer"/>
		               <xsl:param name="suffix" as="xs:string"/>
		               <xsl:variable name="text-string" select="normalize-space(string($text))"/>
		               <xsl:variable name="regex" select="concat('^([^\s]+\s*){1,', $words, '}')"/>
		               <xsl:if test="$text-string">
			                   <xsl:analyze-string select="$text-string" regex="{$regex}" flags="s">
				                       <xsl:matching-substring >
					                           <xsl:value-of select="concat(regex-group(0), $suffix)"/>
				                       </xsl:matching-substring>
			                   </xsl:analyze-string>
		               </xsl:if>
	           </xsl:function>