用JavaScript替换字符之间的所有内容 [英] Replace all content between characters with JavaScript

查看:301
本文介绍了用JavaScript替换字符之间的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的markdown转换器,以使JS和Regex更好.

I'm attempting to make a simple markdown converter to get better at JS and Regex.

我现在需要找到两个星号之间的所有内容,并将它们包装在<i>标记中:

I now need to find everything between two asterisks, and wrap them in <i> tags:

JSFIDDLE

var html = '*abc is a string*';

var html = html.replace(/\*/g , '<i>');

console.log(html);

结果:

<i>abc is a string<i>

我也看到了一个相关问题的答案,但是我不确定如何相应地调整代码或代码的实际作用:

I have also seen an answer to a related question, but I'm unsure how to adjust my code accordingly, or what it actually does:

(?s)<h1>.+</h1>

任何帮助都会很棒.

推荐答案

您可以使用捕获组以获得应包装在HTML标记中的内容:

You can use a capture group to get the content that should be wrapped in the HTML tags:

var html = html.replace(/\*([^*]+)\*/g , '<i>$1</i>');

([^*]+)的解释:

(        # start of capture group
  [^     # start of negated character class (match any character not listed)
    *    # literal asterisk character
  ]      # end of negated character class
  +      # match at least one of the previous token
)        # end of capture group

所以[^*]+的意思是匹配至少一个不是*的字符".这样的结果是,直到下一个*的所有字符都将匹配.

So [^*]+ means "match at least one character that is not *". This has the effect that all characters up to the next * are matched.

这篇关于用JavaScript替换字符之间的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆