简体   繁体   English

使用RegEx创建具有类名的div

[英]Using RegEx to create div with classname

Using RegEx, I want to replace construction in my example into a div. 使用RegEx,我想将示例中的结构替换为div。

So, before: 因此,之前:

::: foo
some text
:::

After: 后:

<div class="foo">
some text
</div>

I found how it may be done ( test ), but my solution works for only one class. 我找到了可能的方法( 测试 ),但是我的解决方案仅适用于一堂课。 In other words, class is hard-coded into script: 换句话说,类被硬编码为脚本:

<script>
document.body.innerHTML = document.body.innerHTML.replace(new RegExp(/(:::\s?[a-z])\w+/, 'g'), '<div class="foo">');
document.body.innerHTML = document.body.innerHTML.replace(new RegExp(/:::/, 'g'), '</div>');
</script>

How it may be changed, so it will work for any class name? 如何更改它,使其适用于任何类名? For example, these constructions should be also converted into divs: 例如,这些构造也应转换为div:

::: foobarfoo
some text
:::

and

::: foo-bar-foo_bar_foo123-foo
some text
:::

You can use capturing groups , that is, put part of your regex in parentheses and then that part of the match will be captured for use in the replacement, where you can reference it with $1 : 您可以使用捕获组 ,即将正则表达式的一部分放在括号中,然后将匹配的那部分捕获以用于替换,您可以在其中使用$1进行引用:

var text = document.body.innerHTML;
text = text.replace(/:::\s?([^\s:]+)/g, '<div class="$1">')
text = text.replace(/:::/g, '</div>');
document.body.innerHTML = text;

If you had more than one capturing group in the same regex the second and subsequent ones would be referenced by $2 , $3 , etc. 如果您在同一个正则表达式中有多个捕获组,则第二个及后续捕获组将由$2$3等引用。

Note that you should avoid repeatedly updating document.body.innerHTML - better to put the original text into a variable, then do your replacements with that variable, then finally write the end result back to document.body.innerHTML . 请注意,您应该避免重复更新document.body.innerHTML最好将原始文本放入变量中,然后用该变量进行替换,最后将最终结果写回到document.body.innerHTML You can also chain the .replace() calls: 您还可以链接.replace()调用:

document.body.innerHTML = document.body.innerHTML
                           .replace(/:::\s?([^\s:]+)/g, '<div class="$1">')
                           .replace(/:::/g, '</div>');

Note also that you don't need to call new RegExp() , because the / at the beginning and end of the regex is the regex literal syntax that creates a regular expression object on its own. 还要注意,您不需要调用new RegExp() ,因为在regex开头和结尾处的/是用于自行创建正则表达式对象的regex文字语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM