"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Achieve Case-Insensitive Searching in XPath Using the contains() Function?

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

Published on 2024-11-07
Browse:948

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'
  )
]

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:

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");

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.
Release Statement This article is reprinted at: 1729589295 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3