Recipe2.1.Testing If a String Ends with Another String


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.





XSLT Cookbook
XSLT Cookbook: Solutions and Examples for XML and XSLT Developers, 2nd Edition
ISBN: 0596009747
EAN: 2147483647
Year: 2003
Pages: 208
Authors: Sal Mangano

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net