Previous Page Next Page

Recipe 2.1. Testing If a String Ends with Another String

Problem

You need to test if 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 contains a native starts-with() function but no ends-with() . This is rectified in 2.0. However, as the previous 1.0 code shows, ends-with can be implemented easily in terms of substring( ) and string-length() . The code simply extracts the last string-length($substr) characters from the target string and compares them to the substring.

Programmers accustomed to having the first position in a string start at index 0 should note that XSLT strings start at index 1.



Previous Page Next Page