对于单个的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
方法。
必读阅读:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 –
什么是创建HTML?也许这比改变后处理更容易,比后处理什么坏了首先... – Tomalak
@Gaby aka G. Petrioli我见过,我认为我的东西是不同的 – Omu