Regular Expressions || How to get a "wildcard" in, specifically replace() function

Viewed 55

I have the following problem, in my replace code I need to found a hole thing, lets say :Hello: and the idea is to find all the word, the full word, and change only the ";" but I am not searching a replacement for :, for all of it, like a wildcard, like a * in CSS, for now I have this

var p = document.querySelector("#div1").innerText
document.write(p.replace(/(hi\[\'*)/g, 'hi(\''));

My idea is to find something than is like /(hi\[\'*\'\])/g

But this exactly wont work

So the result would change from

hi['world']

to

hithere('world')
1 Answers

You can use

console.log("some hi['1 2 3!']".replace(/\bhi\[('.*?')]/g, 'hithere($1)'))

See the regex demo.

Details:

  • \b - a word boundary (the current location must be preceded with a space, punctuation (other than _) or start of string
  • hi\[ - hi[ text
  • ('.*?') - Capturing group 1: a ', then any zero or more chars other than line break chars, as few as possible, and then a '
  • ] - a ] char.
Related