[英]replace all \n with <br/>, all which are not inside <textarea> </textarea> tags
having a javascript string 有一个javascript字符串
var s = ' hi there \n <textarea> hello \n there </texarea> hi \n hi';
anybody knows how to do a replace of \\n
to <br/>
that will only affect the \\n
symbols outside of the textarea ? 任何人都知道如何做一个替换的
\\n
到<br/>
只会影响\\n
textarea的以外的符号?
the result should be this: 结果应该是这样的:
'hi there <br/> <textarea> hello \n there </texarea> hi <br/> hi';
For a single textarea, you can use match
to select the textarea. 对于单个textarea,您可以使用
match
来选择textarea。 Then, use replace
using a Regular expression with the global flag to replace all newlines by <br/>
. 然后,使用
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/>"
If you have to support multiple textareas, you can use a for
loop in conjunction with the exec
method of the Regular expression object. 如果必须支持多个textareas,则可以将
for
循环与正则表达式对象的exec
方法结合使用。
You can use this line 你可以使用这一行
var text = text.replace(/\n/g, '<br/>');
This will replace all \\n characters with 这将替换所有\\ n字符
tag in text. 标签在文本中。
Put everything in a div and put the \\n tags you want in spans. 将所有内容放入div中,并将所需的\\ n标记放在跨度中。 So the first \\n would be the first child and the second \\n outside the text area would be the last child.
所以第一个\\ n将是第一个孩子,文本区域外的第二个\\ n将是最后一个孩子。
Then you can call the first and last child of the div and manipulate the HTML 然后,您可以调用div的第一个和最后一个子节点并操纵HTML
var s = ' hi there <span class= "changethis">\n</span> <textarea> hello \n there </texarea> hi <span class= "changethis">\n</span> hi';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.