jquery 用未知字符替换 text() 中的字符串

标签 jquery string text replace

我想替换,在文本变量中添加一些字符串,以便“包装”我的内容,然后稍后追加它。

例如,我的字符串 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_...] 除外 也许我需要使用与替换不同的函数,我真的不知道......

最佳答案

真的不擅长正则表达式,但我认为这应该有效:

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

http://jsfiddle.net/ujVrD/

关于jquery 用未知字符替换 text() 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20983160/

相关文章:

c++ - C++中getline的段错误

python - 如何更改Elpy自动完成框的颜色而不首先显示私有(private)变量

command-line - 一个衬里逐 block 提取数据

JavaScript 类扩展了 onclick 函数

javascript - 向 .AppendTo 添加可用按钮 - Jquery

c# - 有没有一种简单的方法可以将序数数字字符串转换为其匹配的数值?

Javascript 正则表达式查找可以跨多行中断的特定字符串

winapi - 透明的 win32 窗口和文本

jQuery UI 可排序动画

jquery - 半六边形悬停效果