"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 Perform Case-Insensitive XPath Searching with ContainsIn Function?

How to Perform Case-Insensitive XPath Searching with ContainsIn Function?

Published on 2024-11-12
Browse:487

How to Perform Case-Insensitive XPath Searching with ContainsIn Function?

Case-insensitive XPath Contains

In XPath, the contains() function checks if one string contains another, like this:

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

This is case-sensitive, meaning it won't match "Test," "TEST," or "TesT." To enable case-insensitivity, try this workaround:

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

This replaces every uppercase letter with its lowercase counterpart before checking for matches. However, it's limited to known character sets.

An alternative method leverages 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");

This allows for case-insensitive matching of any search string without prior knowledge of the alphabet. However, both options struggle with single quotes in search strings.

Release Statement This article is reprinted at: 1729588881 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