JavaScript中不区分大小写的字符串替换? [英] Case insensitive string replacement in JavaScript?

查看:1328
本文介绍了JavaScript中不区分大小写的字符串替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在JavaScript字符串中给出关键字,不区分大小写。

I need to highlight, case insensitively, given keywords in a JavaScript string.

例如:


  • 高亮显示(foobar Foo bar FOO,foo)应返回< b> foo< / b> bar< b> Foo< / b> bar< b> FOO< / b>

  • highlight("foobar Foo bar FOO", "foo") should return "<b>foo</b>bar <b>Foo</b> bar <b>FOO</b>"

我需要代码适用于任何关键字,因此使用硬编码的正则表达式(如 / foo / i )不是一个充分的解决方案。

I need the code to work for any keyword, and therefore using a hardcoded regular expression like /foo/i is not a sufficient solution.

最简单的方法是什么?

(这是标题中详述的更一般问题的一个实例,但我觉得最好用一个具体的,有用的例子来解决。)

(This an instance of a more general problem detailed in the title, but I feel that it's best to tackle with a concrete, useful example.)

推荐答案

可以使用正则表达式如果您准备搜索字符串。在PHP中,例如有一个函数preg_quote,用它们的转义版本替换字符串中的所有正则表达式。

You can use regular expressions if you prepare the search string. In PHP e.g. there is a function preg_quote, which replaces all regex-chars in a string with their escaped versions.

这是javascript的这样一个函数:

Here is such a function for javascript:

function preg_quote( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: booeyOH
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: preg_quote("$40");
    // *     returns 1: '\$40'
    // *     example 2: preg_quote("*RRRING* Hello?");
    // *     returns 2: '\*RRRING\* Hello\?'
    // *     example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
    // *     returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'

    return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}

(摘自 http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_preg_quote/

所以你可以做以下事情:

So you coudl do the following:

function highlight( data, search )
{
    return data.replace( new RegExp( "(" + preg_quote( search ) + ")" , 'gi' ), "<b>$1</b>" );
}

这篇关于JavaScript中不区分大小写的字符串替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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