Home >Web Front-end >JS Tutorial >How to Achieve Case-Insensitive Searching in XPath Using the contains() Function?
Case-Insensitive XPath contains() Function
In XPath, the contains() function is case-sensitive. However, there are ways to work around this limitation.
Method 1: Translate Characters
This method involves translating characters to lowercase or uppercase before checking for the substring:
/html/body//text()[ contains( translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'test' ) ]
This converts all uppercase letters in the text to lowercase before checking for the substring "test."
Method 2: Dynamic XPath Expression
Using a scripting language like JavaScript, you can construct a dynamic XPath expression that handles case insensitivity:
<code class="javascript">function xpathPrepare(xpath, searchString) { return xpath.replace("$u", searchString.toUpperCase()) .replace("$l", searchString.toLowerCase()) .replace("$s", searchString.toLowerCase()); } xp = xpathPrepare("//text()[contains(translate(., '$u', '$l'), '$s')]", "Test");</code>
This replaces placeholders in the XPath expression with uppercase, lowercase, and lowercase versions of the search string.
Additional Considerations
The above is the detailed content of How to Achieve Case-Insensitive Searching in XPath Using the contains() Function?. For more information, please follow other related articles on the PHP Chinese website!