使用 JavaScript 替换方法保留大小写/大写 [英] Preserving case / capitalization with JavaScript replace method

查看:41
本文介绍了使用 JavaScript 替换方法保留大小写/大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在继续使用 Jquery UI 开发搜索词建议工具.我现在正在使用粗体显示搜索词模式的结果.我已经通过修补自动完成的 _renderItem 方法实现了这个功能.我现在遇到的问题是替换的字符与用户在输入中键入的字符具有相同的大小写(例如,如果用户输入了A"并且返回的结果是America",则替换的文本将是 AmericA.代码如下:

I'm continuing work on a search term suggestion tool using Jquery UI. I am now working on displaying the results with the search term pattern in bold. I have implemented this functionality through patching the Autocomplete's _renderItem method. The problem I have now is that the replaced characters have the same case as those typed by the user in the input (e.g. if the user typed an "A" and the returned result was "America", the replaced text would be AmericA. Here's the code:

    var exp = new RegExp(this.term, "gi") ;
    var rep = item.label.replace( exp, "<span style='font-weight:bold;color:Black;'>"
    + this.term + "</span>");

与往常一样,提前感谢您的帮助.

As always, thanks in advance for any help.

推荐答案

您可以使用:

var rep = item.label.replace(exp,
                             "<span style='font-weight:bold;color:Black;'>$&</span>");

替换字符串时,$& 表示整个匹配",因此您不必重复搜索词(在某些情况下您不知道).在其他风格中,您可以使用 $0\0.
另外,请记住在 this.term 中转义特殊字符.

When replacing a string, $& means "the whole match", so you don't have to repeat the search term (in some cases you don't know it). In other flavors, you may use $0 or \0.
Also, remember to escape special characters in this.term.

这篇关于使用 JavaScript 替换方法保留大小写/大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆