2014-01-07 69 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