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

Can XPath Queries Become Case-Insensitive Using contains()?

Susan Sarandon
Release: 2024-10-22 20:45:35
Original
848 people have browsed it

Can XPath Queries Become Case-Insensitive Using contains()?

Case-Insensitive XPath contains() Function

Question:

Can XPath queries be made case-insensitive when using the contains() function to search for text nodes?

Answer:

Yes, case-insensitive XPath queries are possible using the following techniques:

Using translate() and contains():

This method involves translating the node value and the search string to lowercase before using the contains() function:

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

Using Host Language to Build Dynamic XPath Expression:

If possible, create a dynamic XPath expression using a host language like 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>
Copy after login

This method translates only the necessary characters in the search string, making it suitable for any search term.

Considerations:

  • Both methods fail when search strings contain single quotes.
  • Using special elements like to mark relevant text can simplify XPath queries.

The above is the detailed content of Can XPath Queries Become Case-Insensitive Using contains()?. 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
Latest Articles by Author
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!