3

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***'))

is giving

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

I was motivated by https://stackoverflow.com/a/19161971/1904943 , and also tried https://stackoverflow.com/a/494046/1904943

Once working, I'll be replacing the '***' (solely for testing / illustration) with HTML code.

Victoria Stuart
  • 4,610
  • 2
  • 44
  • 37

3 Answers3

1

You need create regex expression using RegExp -

var reg = new RegExp(`(${query})`, "gi")

var doc = "DNA deoxyribonucleic acid";
var query = "dna"
var exp = `(${query})`
var reg = new RegExp(exp, "gi")
var result = doc.replaceAll(reg, "***$1***");
console.log(result);
Nikhil Patil
  • 2,480
  • 1
  • 7
  • 20
0

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'))
IvanD
  • 2,728
  • 14
  • 26
  • Love both of these answers (@IvanD | @Nikhil Patel); accepting IvanD's as the function looks quite useful, generally and I learned something new! Many thanks to all who replied!! :-D – Victoria Stuart Dec 23 '20 at 06:49
0

JavaScript's replace already has the functionality of doing a case-insensitive search while also retaining the original case of a capture group, e.g.

var input = "DNA deoxyribonucleic acid";
var output = input.replace(/(dna)/ig, "***$1***");
console.log(output);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360