当前位置:Gxlcms > JavaScript > JS关键字变色实现思路及代码_javascript技巧

JS关键字变色实现思路及代码_javascript技巧

时间:2021-07-01 10:21:17 帮助过:3人阅读

1.替换关键字,对字体变色
代码如下:

public static string ReplaceRed(string strtitle, string redkey)
{
if (redkey == "" || redkey == null)
{
return strtitle;
}
else
strtitle = strtitle.Replace(redkey, " " + redkey + " ");
return strtitle;
}

该方法缺点是:点字符是含大小写的英文时,变色后统一替换为了关键字的大小写,体验不好。
2.用正则,CSS背景变色
代码如下:

protected string HighlightText(string inputText,string searchWord)
{
System.Text.RegularExpressions.Regex expression = new System.Text.RegularExpressions.Regex(searchWord.Replace(" ", "|"), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
return expression.Replace(inputText,new System.Text.RegularExpressions.MatchEvaluator(ReplaceKeywords));
}
public string ReplaceKeywords(System.Text.RegularExpressions.Match m)
{
return "" + m.Value + "";//关键字背景加色
//return "" + m.Value + "";//关键字变色
}

该方法可结合前台JS调用
代码如下:



代码如下: