Home > Web Front-end > JS Tutorial > How to Perform Case-Insensitive XPath Searching with ContainsIn Function?

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

Patricia Arquette
Release: 2024-10-22 18:51:03
Original
279 people have browsed it

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')]
Copy after login

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'
    )
]
Copy after login

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:

<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 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.

The above is the detailed content of How to Perform Case-Insensitive XPath Searching with ContainsIn 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