Home >Web Front-end >JS Tutorial >How to Perform Case-Insensitive XPath Searching with ContainsIn Function?
Case-insensitive XPath Contains
In XPath, the contains() function checks if one string contains another, like this:
/html/body//text()[contains(.,'test')]
This is case-sensitive, meaning it won't match "Test," "TEST," or "TesT." To enable case-insensitivity, try this workaround:
/html/body//text()[ contains( translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'test' ) ]
This replaces every uppercase letter with its lowercase counterpart before checking for matches. However, it's limited to known character sets.
An alternative method leverages JavaScript:
<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 allows for case-insensitive matching of any search string without prior knowledge of the alphabet. However, both options struggle with single quotes in search strings.
The above is the detailed content of How to Perform Case-Insensitive XPath Searching with ContainsIn Function?. For more information, please follow other related articles on the PHP Chinese website!