I guess you need to use a combination of indexOf, RegEx and substring to find and highlight the position of the word in each string.
See Fiddle here:
https://jsfiddle.net/sxk7qj40/
$('#box').keyup(function () {
const valThis = this.value;
const length = this.value.length;
$('.objType').each(function () {
const text = $(this).text();
const textL = text.toLowerCase();
const position = textL.indexOf(valThis.toLowerCase());
if (position !== -1) {
const matches = text.substring(position, (valThis.length + position));
const regex = new RegExp(matches, 'ig');
const highlighted = text.replace(regex, `<mark>${matches}</mark>`);
$(this).html(highlighted).show();
} else {
$(this).text(text);
$(this).hide();
}
});
});
You would not want to hardcode your substring position at 0, as this will always begin at the start of the string regardless.
Instead, you need to use indexOf, which will return the starting position. You can then use that in the substring to find the starting point that you want to replace. Note that indexOf will return -1 if not found, hence the if statement.
Where to end though? Well, this will come in as a combination of the start position we already have + the string length you just typed.
NOTE: For my own convenience, I used some es2015 features like const and template literals, but you can't use es2015, simply run it through Babel,
or manually replace these parts with var and string concatenation
respectively.
Hope this makes sense?
e.g. ES5 safe:
$('#box').keyup(function () {
var valThis = this.value;
var length = this.value.length;
$('.objType').each(function () {
var text = $(this).text();
var textL = text.toLowerCase();
var position = textL.indexOf(valThis.toLowerCase());
if (position !== -1) {
var matches = text.substring(position, (valThis.length + position));
var regex = new RegExp(matches, 'ig');
var highlighted = text.replace(regex, '<mark>' + matches + '</mark>');
$(this).html(highlighted).show();
} else {
$(this).text(text);
$(this).hide();
}
});
});