Home >Web Front-end >JS Tutorial >How to Perform Case-Insensitive XPath Contains() Searches?
Case Insensitive XPath Contains()
Question:
When using XPath to check for the existence of a string within a text node, such as with the expression /html/body//text()[contains(.,'test')], the search is case-sensitive. How can we make the search case-insensitive in XPath for JavaScript?
Answer:
While there is no straightforward way to perform case-insensitive comparisons in XPath 1.0, there are techniques to achieve a similar result:
/html/body//text()[contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'test')]
This method assumes that the alphabet used is known beforehand, so include any accented characters that may be encountered.
<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"); // -> "//text()[contains(translate(., 'TEST', 'test'), 'test')]"</code>
This allows for case-insensitive searches regardless of the character set used.
Note that these methods may not handle single quotes in search strings correctly. For cases with special characters, alternative approaches may be necessary.
The above is the detailed content of How to Perform Case-Insensitive XPath Contains() Searches?. For more information, please follow other related articles on the PHP Chinese website!