2011-09-19 101 views
3

有一个JavaScript字符串与<br/>全部替换 n,所有这一切都没有内部<textarea></textarea>标签

var s = ' hi there \n <textarea> hello \n there </texarea> hi \n hi'; 

任何人知道如何做一个替代的\n<br/>只会影响外部的\n符号textarea?
结果应该是这样的:

'hi there <br/> <textarea> hello \n there </texarea> hi <br/> hi'; 
+1

必读阅读:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 –

+0

什么是创建HTML?也许这比改变后处理更容易,比后处理什么坏了首先... – Tomalak

+0

@Gaby aka G. Petrioli我见过,我认为我的东西是不同的 – Omu

回答

5

对于单个的textarea,你可以使用match选择文本区域。然后,使用带有全局标志的正则表达式使用replace,以便用<br/>替换所有换行符。

var s = s.replace(/\n/g, "<br//>"); 
//Replace all newline characters by "<br//>" 

var textareaContent = s.match(/<textarea>[\s\S]+?<\/textarea>/i); 
//Preparation: Selects a textarea 

var newString = textareaContent[0].replace(/<br\/\/>/g, "\n"); 
//Preparation: replaces all "<br//>" inside the textarea by "\n" (newline feed) 

s = s.replace(textareaContent[0], newString); 
//Replaces the textarea inside the string by the new textarea (= including "\n") 

var desiredResult = s.replace(/<br\/\/>/g, "<br/>"); 
//Replaces the remaining "<br//>" (the ones outside the textarea) by "<br/>" 

如果必须支持多个文本域,则可以结合使用一个for环与正则表达式对象的exec方法。

+0

'/ /'匹配文本区域的内容? – henko

+0

'\ s'匹配所有的空格字符。 '\ S'(大写)匹配所有非白色字符。因此,[\ S \ s]匹配所有字符(包括换行符,不像'.')。 '[\ S \ s] +?'表示:“匹配足够的字符,以便RE的下一部分可以匹配”。如果您不使用问号,“[\ s \ S] +'将包含”“。 –

+0

那么也许有一个错字?两个'\ s'对我来说似乎都是小写字母。 – henko

0

在一个div将所有的东西,把你的跨度希望\ N个标签。所以第一个\ n将是第一个孩子,而第二个\ n在文本区域之外将是最后一个孩子。

然后你就可以调用div的第一和最后一个子和操纵HTML

var s = ' hi there <span class= "changethis">\n</span> <textarea> hello \n there </texarea> hi <span class= "changethis">\n</span> hi'; 
0

您可以使用此行

var text = text.replace(/\n/g, '<br/>'); 

这将在文本
标签替换所有\ n个字符。

相关问题