0

I have a contentEditable="true" div in which, as I type, I would like to wrap the last word before the caret in strong.

I am trying to use regex for this. I made it work for when I type of the string in the regex statically, but it does not work when I pass the word dynamically via like this:

textBeforeCaret.replace(`/${lastWord}$(?!.*?${lastWord})/`, '<strong>$&</strong>')

Thank you for your help!

Baro
  • 5,300
  • 2
  • 17
  • 39
Jacobdo
  • 1,681
  • 2
  • 18
  • 38
  • 1
    What is the input here? Because `/${lastWord}$(?!.*?${lastWord})/` surrounded by backticks will look for the actual *text* surrounded by forward slashes. This might be what you actually want. Or perhaps you are trying to generate a [dynamic regex](https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression) in which case your method is incorrect. – VLAZ Feb 28 '19 at 14:03
  • Yes, I was trying to make a dyanmic regex, lastWord is being a variable the value of which is pulled from a string. – Jacobdo Feb 28 '19 at 14:06
  • In that case, you need to use the `new RegExp("string with dynamic content" + someVariable)` in order to do that, as per the other question. – VLAZ Feb 28 '19 at 14:09
  • Yes, I understand that, but if I follow the answers given there, I am unable to extract the value that I wish to wrap using "$&". – Jacobdo Feb 28 '19 at 14:11
  • @Jacobdo I think you should update the question showing why that does not help you. – Wiktor Stribiżew Feb 28 '19 at 14:12
  • Never mind, it does work, I was just looking at it wrong. Thank you for pointing it out. – Jacobdo Feb 28 '19 at 14:14

0 Answers0