简体   繁体   English

如果单词的第一个字符匹配,则在字符串列表中搜索任何出现的单词并突出显示匹配的单词。Javascript regex

[英]Search a string for any occurence of a word in a list of strings and higlight matched word if first character of word matches.Javascript regex

Click here This works with [substring of word ][matches].单击此处这适用于 [词的子串][匹配]。 ideally which not match on substring.理想情况下,它与子字符串不匹配。

if searched word first character matches with first character of any words in list of string to be searched.如果搜索的单词第一个字符与要搜索的字符串列表中的任何单词的第一个字符匹配。 matched characters should be highlighted匹配的字符突出显示

 // Core function function buildRegexFor(find) { return '(' + find + ')'; } // Handle button click event document.querySelector('button').onclick = function () { // (1) read input var find = document.querySelector('input').value; var str = document.querySelector('textarea').value; // (2) build regular expression using above function var regexStr = buildRegexFor(find); // (3) apply regular expression to text and highlight all found instances str = str.replace(new RegExp(regexStr, 'g'), "<strong class='boldtxt'>$1</strong>"); // (4) output document.querySelector('span').textContent = regexStr; document.querySelector('div').innerHTML = str; };
 .boldtxt { color: red; }
 Value to find: <br> <input value="eter"> <br> <button>find</button> <br> Text to find in: <br> <textarea cols=40>meter parameter eter water twitter eternal</textarea> <br> Regex: <span></span> <br> <div></div>

. .

words can have special characters as well which has to be highlighted if it matches.单词也可以有特殊字符,如果匹配则必须突出显示。 Below is piece of code which i have tried to achieve.下面是我试图实现的一段代码。 eter nal is only word in which eter should be highlighted, where as eter in Meter and Parameter should not be highlighted. ETER最终只字,其中ETER应该强调,其中在仪表和参数ETER不应该被突出显示。

Change the function that creates the regex to the following将创建正则表达式的函数更改为以下内容

function buildRegexFor(find) {
    return '(\\b' + find +')';
}

that will highlight only the occurrences of the string if they are at the beginning of the word or the word themselves.如果字符串位于单词的开头或单词本身,则只会突出显示字符串的出现。 If I understood your question correctly, that is what you need.如果我正确理解了您的问题,那就是您所需要的。

Thanks谢谢

Paras帕拉斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM