Hello I am trying to create a regex which will grab everything between and including the curly braces only if the string between braces starts with # and if there is a \n after the closing curly brace }
I have this following string as an example -
## Markdown Syntax {#markdown-syntax}\n\n (lorem ipsum test).\n\n## Headers {#headers}\n\n function HelloCodeTitle(props) {return <h1>Hello, {props.name}</h1>; } {2}
In this example, I am looking to extract {#markdown-syntax}
and {#headers}
from the above string and replace them with empty space ''
I have written this regex but this is also grabbing {return <h1>Hello, {props.name}
and {2}
which I do not want. I am only looking to grab {#markdown-syntax}
and {#headers}
(including braces) as the string between braces starts with # and there is a \n after the closing curly brace }
Use match()
with the appropriate pattern:
var input = "## Markdown Syntax {#markdown-syntax}\n\n (lorem ipsum test).\n\n## Headers {#headers}\n\n function HelloCodeTitle(props) {return <h1>Hello, {props.name}</h1>; } {2}"; var tags = input.match(/\{#.*?\}(?=\n)/g, input); console.log(tags);
The regex pattern used above says to:
\{ match opening {
# match #
.*? match all content up the first
\} closing }
(?=\n) assert that what follows is a newline character
If you want to remove these tags, then use replace
with the same pattern:
var input = "## Markdown Syntax {#markdown-syntax}\n\n (lorem ipsum test).\n\n## Headers {#headers}\n\n function HelloCodeTitle(props) {return <h1>Hello, {props.name}</h1>; } {2}"; var output = input.replace(/\s*\{#.*?\}(?=\n)/g, " ").trim(); console.log(output);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.