JavaScript replaceAll 不区分大小写的搜索使用变量而不是字符串 [英] JavaScript replaceAll case-insensitive search using variable rather than a string
问题描述
我想在不区分大小写的搜索中使用变量(而不是字符串)执行 JavaScript replaceAll()
,但同时保留匹配文本的大小写(在返回中).例如,
I want to do a JavaScript replaceAll()
using a variable (rather than a string) in a case-insensitive search, but also retaining the case of the matched text (in the return). For example,
console.log('doc.p:', doc.p.toString().substring(0, 26))
var query = this.manager.store.get('q').value.toString();
console.log('query:', query, '| type:', typeof(query))
console.log(doc.p.toString().replaceAll(/(dna)/gi, '***$1***'))
console.log(doc.p.toString().replaceAll(/(query)/gi, '***$1***'))
正在给予
doc.p: DNA deoxyribonucleic acid // target text
query: dna | type: string // query text
***DNA*** deoxyribonucleic acid ... // [success] case-insensitive search; case-sensitive return
DNA deoxyribonucleic acid ... // [failure] I've also tried (e.g.) $query, $(query), ... here
我受到 https://stackoverflow.com/a/19161971/1904943 的激励,也尝试了
I was motivated by https://stackoverflow.com/a/19161971/1904943 , and also tried https://stackoverflow.com/a/494046/1904943
一旦工作,我将用 HTML 代码替换***"(仅用于测试/插图).
Once working, I'll be replacing the '***' (solely for testing / illustration) with HTML code.
推荐答案
基本上,您想要的是创建动态正则表达式,而不是对其进行硬编码.这是在 的帮助下完成的.RegExp 构造函数,它采用正则表达式和标志的字符串表示(我把字符串大写弄乱了,以演示大小写的保留):
Basically, what you want is to create a dynamic regular expression, instead of hardcoding it. This is done with the help of. RegExp constructor, which takes the string representation of a regexp and flags (I messed the string capitalization to demo the preservation of case):
string1 = 'DnA deoxyribonucleic acid'
string2 = 'DNA deoxyribonucleic aCId'
const replacer = (str, replace) => {
const re = new RegExp(`(${replace})`, 'gi')
return str.replaceAll(re, '***$1***')
}
console.log(replacer(string1, 'dna'))
console.log(replacer(string2, 'acid'))
这篇关于JavaScript replaceAll 不区分大小写的搜索使用变量而不是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!