【问题标题】:jquery replace string from text() with unknown charactersjquery 用未知字符替换 text() 中的字符串
【发布时间】:2014-01-25 19:35:24
【问题描述】:

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

例如,我的字符串 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的函数,我真的不知道......

【问题讨论】:

    标签: jquery string text replace


    【解决方案1】:

    我可以引导你到jQuerys .wrap() method。它获取您选择的元素并用您在方法第一个参数中定义的标签包装它们。在您的情况下,这将是.wrap('&lt;p&gt;&lt;/p&gt;')。我希望这会有所帮助。

    【讨论】:

    • 感谢您的回答,但我无法包装它,因为它来自字符串 var。我不想包装到 DOM 中。我想将 div 容器子文本放入 var 然后替换一些字符串...
    【解决方案2】:

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

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

    http://jsfiddle.net/ujVrD/

    【讨论】:

    • 谢谢!奇迹般有效。你能解释一下这个正则表达式的过程吗?我对这种东西很不熟悉......
    • @lolo 不客气,第一个.replace() 调用会替换] ... [ 之间的所有字符。第二个替换所有以[开头并以]结尾的第二个参数,$1指的是正则表达式中(...)之间的匹配字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多