我想在不replaceAll()
区分大小写的搜索中使用变量(而不是字符串)来执行JavaScript ,但还要保留匹配文本的大小写(以返回形式)。例如,
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的激励,还尝试了https://stackoverflow.com/a/494046/1904943
一旦工作,我将用HTML代码替换“ ***”(仅用于测试/插图)。
基本上,您要创建一个动态正则表达式,而不是对其进行硬编码。这是在的帮助下完成的。RegExp构造函数,它使用正则表达式的字符串表示形式和标志(我弄乱了字符串大写以演示大小写的保留):
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'))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句