XML technologies / XSLT / XSLT Kochbuch / Strings / Testing whether a string ends with another string

(Excerpt from "XSLT Kochbuch" by Sal Mangano)

Problem

You need to test whether a string ends with a particular substring.

Solution

XSLT 1.0

substring($value, (string-length($value) - string-length($substr)) + 1) = $substr

XSLT 2.0

ends-with($value, $substr)

Discussion

XSLT 1.0 includes the built-in function starts-with(), but no ends-with() function. This omission was addressed in 2.0. However, as the 1.0 code shows, ends-with() can easily be implemented using substring() and string-length(). The code simply extracts the last string-length($substr) characters from the target string and compares them with the substring.

Warning!
Programmers accustomed to the first position in a string having index 0 must remember that XSLT strings start at index 1.

  

 

 

 

back to top