我要替换,在text var中添加一些字符串以“包装”我的内容,然后稍后再添加。

例如,我在字符串var中有这个(在我的var中没有换行符):

[th_section type="boxed" bgcolor="" txtcolor=""]
[th_header type="h1" txtalign="txt-left" subtitle="essai subtitle" txtcolor=""]
HEADER 1
[/th_header]
[th_five_sixths txtalign="txt-left" boxed="" last_column="true"]
[th_header type="h5" txtalign="txt-left" subtitle="" txtcolor=""]
100% Responsive Design
[/th_header]
Phasellus enim libero, blandit vel sapien vitae, condimentum ultricies magna et. Quisque euismod orci ut et lobortis aliquam.
[/th_five_sixths]
[/th_section]


而且我想像这样替换/添加p标签:

<p>[th_section type="boxed" bgcolor="" txtcolor=""]</p>
<p>[th_header type="h1" txtalign="txt-left" subtitle="essai subtitle" txtcolor=""]</p>
<p>HEADER 1</p>
<p>[/th_header]</p>
<p>[th_five_sixths txtalign="txt-left" boxed="" last_column="true"]</p>
<p>[th_header type="h5" txtalign="txt-left" subtitle="" txtcolor=""]</p>
<p>100% Responsive Design</p>
<p>[/th_header]</p>
<p>Phasellus enim libero, blandit vel sapien vitae, condimentum ultricies magna et. Quisque euismod orci ut et lobortis aliquam.</p>
<p>[/th_five_sixths]</p>
<p>[/th_section]</p>


实际上,我搜索这样的正则表达式可能是:

$someDiv.replace('[th_*******]', '<p>[th_*******]</p>').replace('[/th_*******]', '<p>[/th_*******]</p>')


我不知道在这种情况下使用替换的正确方法是什么。括号之间的名称可以不同,除了[th _...]和[/ th _...]
也许我需要使用不同于replace的功能,我真的不知道...

最佳答案

我真的对正则表达式不好,但是我认为这应该起作用:

theString.replace(/\]([^\[]+)/g, function(m) {
   return "]<p>" + m.slice(1) + "</p>";
}).replace(/(\[.*?\])/g, "<p>$1</p>");  // /(\[\/?th_[^\]]*\])/g


http://jsfiddle.net/ujVrD/

09-25 17:15
查看更多