The contains()
function in XPath is used to check if a string contains a specified substring. It returns a boolean value of true
if the string contains the specified substring, and false
if it does not.
Here is an example of how to use the contains()
function in XPath:
// Select all elements whose text content contains the substring "apple"
// For example, the following element would be selected: <div>I love eating apples</div>
// But the following element would not be selected: <div>I love eating bananas</div>
// The XPath expression would be:
// //*[contains(text(), 'apple')]
In this example, the contains()
function is used to select all elements whose text content contains the substring “apple”. The text()
function is used to select the text content of the element, and the contains()
function checks if this text content contains the specified substring.
The contains()
function is case-sensitive, so the substring “apple” and “Apple” would be treated as different substrings. If you want to perform a case-insensitive search, you can use the translate()
function to convert the text to uppercase or lowercase before using the contains()
function.
// Select all elements whose text content contains the substring "apple" (case-insensitive)
// The XPath expression would be:
// //*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'apple')]
In this example, the translate()
function is used to convert the text to lowercase before using the contains()
function. This allows the contains()
function to perform a case-insensitive search for the substring “apple”.