2014-01-07 70 views
2

我想要替换,在文本var中添加一些字符串以便“包装”我的内容,然后稍后添加它。jquery从文本()替换字符串()与未知字符

比如我在字符串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 _...] 也许我需要使用不同于替换的功能,我真的不知道...

回答

1

我真的在正则表达式,但我认为这应该工作:

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

http://jsfiddle.net/ujVrD/

+0

谢谢!奇迹般有效。你能解释一下这个正则表达式的过程吗?我很不熟悉这种东西...... – lolo

+0

@lolo欢迎您,第一个'.replace()'调用替换'] ... ['之间的所有字符。第二个用'['开头,用']'结尾用第二个参数替换,'$ 1'指向正则表达式中的'(...)'之间的匹配字符串。 – undefined

+0

好的!万分感谢! – lolo

0

可能我直接你到jQuerys .wrap() method。它把你选择的元素和用你在方法第一个参数中定义的标签包装起来。在你的情况下,这将是.wrap('<p></p>')。我希望这有帮助。

+0

感谢您的答案,但因为它来自一个字符串变种我不能把它包装。我不想包装到DOM中。我想把div容器儿童文字放在一个var然后替换一些字符串... – lolo