最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - replace all lines starting with - Stack Overflow

programmeradmin6浏览0评论

How to replace all lines in multiline string starting with #

str.replace(/^#([^\n]*)\n$/gm, '<h1>$1</h1>')

multiline string

# headline
some text

# new headline
some more text

result string

<h1>headline</h1>
some text

<h1>new headline</h1>
some more text

How to replace all lines in multiline string starting with #

str.replace(/^#([^\n]*)\n$/gm, '<h1>$1</h1>')

multiline string

# headline
some text

# new headline
some more text

result string

<h1>headline</h1>
some text

<h1>new headline</h1>
some more text
Share Improve this question edited Nov 18, 2013 at 12:33 clarkk asked Nov 18, 2013 at 12:28 clarkkclarkk 1 1
  • So the goal is to match everything from any start-of-line + hash to the closest end-of-line? Why does that feel trivial to me? – John Dvorak Commented Nov 18, 2013 at 12:31
Add a ment  | 

3 Answers 3

Reset to default 8

try this regexp /^#(.*)$/mg like this

str.replace(/^#(.*)$/mg,"<h1>$1</h1")

If your line breaks are \n, then this will work:

#(.*?)(\n|$)

Javascript:

str.replace(/#(.*?)(\n|$)/g,"<h1>$1</h1>")

^#\s(\w+)$ Will match any line beginning with a #, followed by a single whitespace character and then followed by at least 1 word character (A-Z, 0-9 and underscores). It then stores a match group of the headline text.

You should be able to call this match group with \1.

发布评论

评论列表(0)

  1. 暂无评论