Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find substring in Javascript and prepend/append some characters

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...

like image 498
ARW Avatar asked Feb 19 '23 10:02

ARW


1 Answers

thestring.replace(/~(\w+)/g, "#$1#");

The parentheses "capture" the word (\w+) and the $1 in the result references what's captured.

like image 110
Matt S Avatar answered May 01 '23 12:05

Matt S