Imagine I have the following multi-line Javascript string:
school
apple
~carrot
dog
I want to take any line that starts with "~" and replace it with "#(contents of line)#". So in this example I want to find "~carrot" and replace it with "#carrot#".
I'm trying to come up with a solution using regular expressions but can't figure out a way to replace some matched string with a modified version of itself (with the prepended/appended characters.)
Any help would be appreciated, hoping one example will turn on the lightbulb...
thestring.replace(/~(\w+)/g, "#$1#");
The parentheses "capture" the word (\w+
) and the $1
in the result references what's captured.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With