Javascript: replace all the literal or regexpr occurrences in a string
Mar 27, 2023
Replace FIRST occurrence only
“aaaaa”.replace(“a”, “b”) // baaaa
Replace ALL occurrences
“aaaaa”.replaceAll(“a”, “b”) // bbbbb
Advanced replaceAll using Rgexpr
Example with markdown, replacing titles with HTML tags
#this is the title
content
# another title
another content
to transform into
<h1>this is the title</h1>
content
<h1>another title</h1>
another content
This can be done with replaceAll taking all the content after a # symbol and spaces until the next line and outputting it inside h1 tags. Note that $1 means the content inside the first set of brackets.
stringAbove.replaceAll(/\n# *(.*) *\n/g, '\n<h1>$1</h1>\n')
Note also the usage of /g
. this is necessary to include ALL the lines. Without that modifier, only the first line will be replaced.
Clap if useful, Follow me for more