Adrikks,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
label {
display: flex;
flex-direction: column;
}
#result mark {
color: #FF0000;
}
</style>
</head>
<body>
<label>
Исходная строка:
<input id="text" placeholder="Введите текст..." value="главный врач 12345 главный сан врач">
</label>
<label>
Искомые совпадения:
<input id="search" placeholder="Введите текст..." value="гл вр">
</label>
<p id="result"></p>
<script>
RegExp.escape = s => s.replace(/[[\\^$.|?*+()]/gim, "\\$&");
function mark(string) {
const node = document.createElement("mark");
node.textContent = string;
return node;
}
search.addEventListener("input", () => {
const value = text.value.match(/\s+|\S+/g);
let parts = search.value.trim();
const length = parts.length;
if(!value || !length) {result.textContent = text.value; return};
parts = parts.split(/\s+/).map(pattern => new RegExp("(\\S*?)(" +RegExp.escape(pattern) +")(\\S*)", "i"));
result.textContent = "";
let temp = [];
for (let i = 0; i < value.length; ) {
let k = i, arrFindIndex = [];
let found = parts.every(reg => {
let index = value.slice(k).findIndex(el => reg.test(el));
if(index === -1 ) return false;
k += index;
arrFindIndex.push({k,reg});
k++;
return true
});
if(found) {i = k; temp.push(...arrFindIndex)}
else i++;
}
value.forEach((el, i) => {
const find = temp.find(({k}) => k == i);
if(find){
const {reg} = find;
[_, ...el]= el.match(reg);
el[1] = mark(el[1])
result.append(
...el
)
}
else result.append(el)
})
});
search.dispatchEvent(new Event("input"));
</script>
</body>
</html>