ios regex lookbehind not supported

214 Views Asked by At

i am using a regex to search through html and highlight results. it works very well in all but ios version < 16.4 because they dont support regex lookbehind. can someone help me change my regex because i have tried several alternative but they never leave the html image tags alone :-(

const regex = new RegExp('(?<!</?[^>]*|&[^;]*)(' + $search.value + ')', 'gi');

i get the following error in safari: Invalid regular expression: invalid group specifier name

i have read about putting (?<!</ into a non-captured group but cant get it working

changed

(?<!</

into

(?:</

now it doesn't match anything anymore

1

There are 1 best solutions below

0
Vincent F On

You could try:

  • Solution 1: escape the < (supposing the look ahead is not the problem)
  • Solution 2: remove the look ahead and just call the group capture. Because using look ahead is not necessary when using capture groups.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Regex Search Demo</title>
</head>
<body>

<p id="content">Hello, this is a sample <a href="#">text</a> for search. Also, here's an &text; entity.</p>
<p>Full match: <span id="fullMatch"></span></p>
<p>Captured group: <span id="capturedGroup"></span></p>

<script>
    let $search = { value: "text" };

    let str = document.getElementById('content').textContent; // Using textContent to ignore HTML tags

    // Create a regex pattern based on $search.value
    
    /* Your regex: */
    // let regexPattern = new RegExp('(?<!</?[^>]*|&[^;]*)(' + $search.value + ')', 'gi');
    
    /* Solution 1: escaping the < */
    //let regexPattern = new RegExp('(?<!\</?[^>]*|&[^;]*)(' + $search.value + ')', 'gi');
    
    /* Solution 2: without lookahead. Just use the capture group */
    let regexPattern = new RegExp('!</?[^>]*|&[^;]*(' + $search.value + ')', 'gi');


    // Execute regex pattern
    let groupResult = regexPattern.exec(str);

    if (groupResult) {
        document.getElementById('fullMatch').textContent = groupResult[0]; // Display the full match

        if (groupResult[1]) {
            document.getElementById('capturedGroup').textContent = groupResult[1]; // Display the captured group
        } else {
            document.getElementById('capturedGroup').textContent = "No captured group found.";
        }

    } else {
        document.getElementById('fullMatch').textContent = "No match found.";
        document.getElementById('capturedGroup').textContent = "No captured group found.";
    }
</script>

</body>
</html>
``