0

The following method highlights substrings of a large string. What I want is to support a special character * which represents any string of any length. For example, if * is inputted in the search text field, the whole loaded text file should be highlighted. When the input becomes *a, all the words that end with 'a' should be highlighted. 'a' matches all the words that contain a. However, at the moment * character is not even picked up. What can I do to fix this problem? Thanks in advance..

function search() {
    var hid = document.getElementById('hidtxt').value;
    if(hid.length == 0) hid.value=document.getElementById("input").innerHTML;
        var text = document.getElementById("searchText").value;
       if (!text) return;
        var regex =  new RegExp(text, 'gi');
            document.getElementById("input").innerHTML = hid.replace(regex, '<span style="background-color:yellow;">$&</span>');


    }
4

1 回答 1

0

I don't think you can make such a straightforward translation of the input field into regex.

The asterisk on its own won't match as it has to be .* to be a valid regex.

Other cases will get even more complex, e.g. for an input string blah bla bl bla *837465jfbnrja

.*a would match the whole string while what you probably are after is to get bla bla and *837465jfbnrja as separate matches (as you mention highlighting words)

To make that work the regex would need to be non-greedy matching of everything that is NOT a whitespace character:

\b(?:[^\s])*?a\b

Try some combinations out here and you'll get the idea:

http://regexpal.com/

You'd need to come up with a fixed set of rules that you want to allow, then you can prepare a translation of the allowed special characters into regex to make it work.

于 2013-05-14T07:03:08.473 回答