使用JavaScript进行一些文本交换(推荐/淡入淡出),并希望在引号内插入等效的<br/>
,以便引用的作者在下一行。在下面的代码中,我尝试按照JavaScript: How to add line breaks to an HTML textarea?上的说明操作,但我不确定如何插入/\n\r?/g
以使其正常工作。
<script type="text/javascript">
var text = document.forms[0].txt.value;
text = text.replace(/\n\r?/g, '<br />');
</script>
<script type="text/javascript">
window.testimonials = [
'"This was a great experience" /\n\r?/g - Max Cameron, ThinkTank',
'"This was a great experience" /\n\r?/g - Max Cameron, ThinkTank',
"source code"
];
</script>
有没有办法强迫它进入下一行?谢谢!
答案 0 :(得分:3)
小提琴:
http://jsfiddle.net/4Fheu/
试试这个:
<script type="text/javascript">
var text = window.testimonial; // or maybe: document.forms[0].txt.value;
text = text.replace(/\n\r?/g, '<br />');
alert(text);
</script>
<script type="text/javascript">
window.testimonials = [
'"This was a great experience" \n - Max Cameron, ThinkTank',
'"This was a great experience" \n - Max Cameron, ThinkTank',
"source code"
];
</script>
/\n\r?/
是一个正则表达式:'newline'后跟0或1'回车'。
值'/\n\r?/'
是一个字符串,可能如下所示:
/
/
答案 1 :(得分:0)
Borrowing from what you linked to:
window.testimonials = [
'"This was a great experience" /\n\r?/g - Max Cameron, ThinkTank'.replace(/(\n\r?)|(,)/g, '<br />');,
'"This was a great experience" /\n\r?/g - Max Cameron, ThinkTank'.replace(/(\n\r?)|(,)/g, '<br />');,
"source code"];