Home > Web Front-end > JS Tutorial > How to Achieve Case-Insensitive Searching in XPath Using the contains() Function?

How to Achieve Case-Insensitive Searching in XPath Using the contains() Function?

Barbara Streisand
Release: 2024-10-22 19:19:31
Original
210 people have browsed it

How to Achieve Case-Insensitive Searching in XPath Using the contains() Function?

Case-Insensitive XPath contains() Function

In XPath, the contains() function is case-sensitive. However, there are ways to work around this limitation.

Method 1: Translate Characters

This method involves translating characters to lowercase or uppercase before checking for the substring:

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

This converts all uppercase letters in the text to lowercase before checking for the substring "test."

Method 2: Dynamic XPath Expression

Using a scripting language like JavaScript, you can construct a dynamic XPath expression that handles case insensitivity:

<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 replaces placeholders in the XPath expression with uppercase, lowercase, and lowercase versions of the search string.

Additional Considerations

  • Both methods assume the alphabet is known.
  • If element text can contain single quotes, escape them to prevent XPath syntax errors.
  • If using Method 2, handle escaped quotes in the search string.

The above is the detailed content of How to Achieve Case-Insensitive Searching in XPath Using the contains() Function?. 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