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

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

问题描述

我需要突出显示 JavaScript 字符串中给定的关键字,不区分大小写.

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

例如:

  • highlight("foobar Foo bar FOO", "foo") 应该返回 "<b>foo</b>bar <b>Foo</b> bar <;b>FOO"

我需要代码适用于任何关键字,因此使用像 /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 的这样一个函数(source):

Here is such a function for javascript (source):

function preg_quote (str, delimiter) {
  //  discuss at: https://locutus.io/php/preg_quote/
  // original by: booeyOH
  // improved by: Ates Goral (https://magnetiq.com)
  // improved by: Kevin van Zonneveld (https://kvz.io)
  // improved by: Brett Zamir (https://brett-zamir.me)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  //   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(new RegExp('[.\\+*?\[\^\]$(){}=!<>|:\' + (delimiter || '') + '-]', 'g'), '\$&')
}

因此您可以执行以下操作:

So you could do the following:

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

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

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