Javascript 如何正确地从Twitter中使用粗体搜索词,JS中奇怪的正则表达式

Javascript 如何正确地从Twitter中使用粗体搜索词,JS中奇怪的正则表达式,javascript,jquery,regex,twitter,Javascript,Jquery,Regex,Twitter,我正在使用Twitter API从Twitter检索推文,并在我自己的客户端中显示它们 然而,我很难正确地突出显示正确的搜索词。我希望得到如下效果: 我在JS中尝试这样做的方式是使用一个名为highlightSearchTerms()的函数,该函数将tweet的文本和一组关键字作为参数加粗。它返回固定tweet的文本。我通过将关键字包装在一个包含class.search术语的文件中来加粗关键字 我有很多问题,包括: 运行简单替换不会保留大小写 与href标记中的关键字存在很多冲突 如果我尝试

我正在使用Twitter API从Twitter检索推文,并在我自己的客户端中显示它们

然而,我很难正确地突出显示正确的搜索词。我希望得到如下效果:

我在JS中尝试这样做的方式是使用一个名为highlightSearchTerms()的函数,该函数将tweet的文本和一组关键字作为参数加粗。它返回固定tweet的文本。我通过将关键字包装在一个包含class.search术语的文件中来加粗关键字

我有很多问题,包括:

  • 运行简单替换不会保留大小写
  • 与href标记中的关键字存在很多冲突
  • 如果我尝试使用替换来执行for循环,我不知道如何只修改href中没有的搜索词,并且我还没有使用上面的span包装这些搜索词
我希望能够处理的推文示例如下:

Input:

This is a keyword. This is a <a href="http://search.twitter.com/q=%23keyword">
#keyword</a> with a hashtag. This is a link with kEyWoRd: 
<a href="http://thiskeyword.com">http://thiskeyword.com</a>.

Expected Output:

This is a 
<span class="search-term">keyword</span>
. This is a <a href="http://search.twitter.com/q=%23keyword"> #
<span class="search-term">keyword</span>
</a> with a hashtag. This is a link with 
<span class="search-term">kEyWoRd</span>
:<a href="http://thiskeyword.com">http://this
<span class="search-term>keyword.com</span>
</a>.
输入:
这是一个关键词。这是一个带有标签的文件。这是一个带有关键字的链接:
.
预期产出:
这是一个
关键词
. 这是一个带有标签的文件。这是一个链接
关键词
:.
我试过很多方法,但不幸的是我没有找到解决问题的正确方法。任何建议都将不胜感激

下面是我的代码,它适用于某些情况,但最终不能满足我的要求。当关键字位于链接的后半部分(例如)时,它无法处理。有时它也会奇怪地在关键字前突出显示2个字符。我怀疑最好的解决方案会太像我的代码

function _highlightSearchTerms(text, keywords){

    for (var i=0;i<keywords.length;i++) {

    // create regex to find all instances of the keyword, catch the links that potentially come before so we can filter them out in the next step
    var searchString = new RegExp("[http://twitter.com/||q=%23]*"+keywords[i], "ig");

    // create an array of all the matched keyword terms in the tweet, we can't simply run a replace all as we need them to retain their initial case
    var keywordOccurencesInitial = text.match(searchString);

    // create an array of the keyword occurences we want to actually use, I'm sure there's a better way to create this array but rather than try to optimize, I just worked with code I know should work because my problem isn't centered around this block
    var keywordOccurences = [];
    if (keywordOccurencesInitial != null) {
        for(var i3=0;i3<keywordOccurencesInitial.length;i3++){
            if (keywordOccurencesInitial[i3].indexOf("http://twitter.com/") > -1 || keywordOccurencesInitial[i3].indexOf("q=%23") > -1) 
                continue;
            else
                keywordOccurences.push(keywordOccurencesInitial[i3]);
        }
    }

    // replace our matches with search term
    // the regex should ensure to NOT catch terms we've already wrapped in the span
    // i took the negative lookbehind workaround from http://stackoverflow.com/a/642746/1610101
    if (keywordOccurences != null) {
        for(var i2=0;i2<keywordOccurences.length;i2++){
            var searchString2 = new RegExp("(q=%23||http://twitter.com/||<span class='search-term'>)?"+keywordOccurences[i2].trim(), "g"); // don't replace what we've alrdy replaced
            text = text.replace(searchString2, 
                function($0,$1){ 
                    return $1?$0:"<span class='search-term'>"+keywordOccurences[i2].trim()+"</span>";
                });
        }
    }

    return text;
}
function\u highlightSearchTerms(文本、关键字){
对于(变量i=0;i-1)
继续;
其他的
关键字Occurences.push(关键字OccurenceSintial[i3]);
}
}
//用搜索词替换我们的匹配项
//正则表达式应该确保不捕捉我们已经包装在span中的术语
//我从http://stackoverflow.com/a/642746/1610101
if(关键字发生!=null){
对于(var i2=0;i2,您可能可以使用:

var getv = document.getElementById('tekt').value;
var keywords = "keyword,big elephant"; // comma delimited keyword list
var rekeywords = "(" + keywords.replace(/\, ?/ig,"|") + ")"; // wraps keywords in ( and ), and changes , to a pipe (character for regex alternation)

var keyrex = new RegExp("(#?\\b" + rekeywords + "\\b)(?=[^>]*?<[^>]*>|(?![^>]*>))","igm")

alert(keyrex);
document.getElementById('tekt').value =  document.getElementById('tekt').value.replace(keyrex,"<span class=\"search-term\">$1</span>");

但请注意,您会遇到一些问题,例如
smiles
以smiles结尾(如果用户搜索mile),而regex对此无能为力。regex对单词的定义是字母数字字符,它没有字典可查。

@DavidThomas好的。我很抱歉。我现在正在格式化并发布它。这几乎是完美的。你知道如何稍微修改它,以便中的关键字也会突出显示吗?
var getv = document.getElementById('tekt').value;
var keywords = "keywords,big elephant";
var rekeywords = "(" + keywords.replace(/(es|ing|ed|d|s|e)?\b(\s*,\s*|$)/ig,"(es|ing|ed|d|s|e)?$2").replace(/,/g,"|") + ")";

var keyrex = new RegExp("(#?\\b" + rekeywords + "\\b)(?=[^>]*?<[^>]*>|(?![^>]*>))","igm")

console.log(keyrex);

document.getElementById('tekt').value =  document.getElementById('tekt').value.replace(keyrex,"<span class=\"search-term\">$1</span>");
var keyrex = new RegExp("(#?\\b" + rekeywords + "\\b)(?=[^>]*?<[^>]*>|(?![^>]*>))","igm")
var keyrex = new RegExp("(#?" + rekeywords + ")(?=[^>]*?<[^>]*>|(?![^>]*>))","igm")