Home > Web Front-end > JS Tutorial > body text

How to Perform Case-Insensitive XPath Contains() Searches?

DDD
Release: 2024-10-22 20:33:39
Original
743 people have browsed it

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:

  1. Translate Character Cases: Utilize the translate() function to convert the text node and the search string to a single case, either upper or lower. For example:
/html/body//text()[contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'test')]
Copy after login

This method assumes that the alphabet used is known beforehand, so include any accented characters that may be encountered.

  1. Dynamic XPath Expression: Create a dynamic XPath expression using a host language like JavaScript. Replace the search string with its upper, lower, and original forms in the contains() clause:
<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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!