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>');
}
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, eg 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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.