Home >Web Front-end >JS Tutorial >How to Achieve Case-Insensitive contains() Functionality in XPath 1.0?

How to Achieve Case-Insensitive contains() Functionality in XPath 1.0?

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 01:17:30687browse

How to Achieve Case-Insensitive contains() Functionality in XPath 1.0?

XPath's Case-Insensitive contains()

In XSLT or other DOM-traversing applications, performing XPath queries with case-sensitive string comparisons can be limiting. However, achieving case-insensitive contains() functionality in XPath 1.0 is possible.

1. Translation-Based Method (XPath 1.0)

To match both case-sensitive and case-insensitive variations of a string, employ the translate() function:

/html/body//text()[
  contains(
    translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),
    'test'
  )
]

This method effectively translates all uppercase letters to lowercase, enabling case-insensitive comparisons. However, it requires knowledge of the expected character set.

2. JavaScript-Assisted Dynamic XPath Generation

If manipulating the XPath expression is possible, you can use JavaScript to dynamically replace the search string with its upper and lowercase variants:

<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 method handles search strings with arbitrary characters, including single quotes.

Caution: These techniques may not perform optimally if complex/large string operations are involved. If possible, consider other solutions such as storing strings with known character sets or adopting XPath 2.0, which natively supports case-insensitive string comparisons.

The above is the detailed content of How to Achieve Case-Insensitive contains() Functionality in XPath 1.0?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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