在javascript函数中插入多行字符串作为变量 [英] inserting multiline string as a variable in a javascript function

查看:86
本文介绍了在javascript函数中插入多行字符串作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过RJS插入一个取自textarea的多行字符串。执行:

I want to insert, via RJS a multiline string taken from a textarea. Doing:

$('#description').text('<%= simple_format description %>');

不起作用,因为它会生成如下内容:

does not work because it will generate something like this:

$('#description').text('<p>first line
<br />second line</p>

<p>fourth line</p>');

因为字符串不在一行上,所以JS调用失败。那么现在simple_format正确地格式化了字符串,如何在RJS文件中将它全部打印在一行?

Because the string isnt on a single line, the JS call fails. So now that simple_format formatted the string correctly, how can I have it all print on a single line in my RJS file?

推荐答案

试试这个:

$('#description').text('<%= simple_format(description).gsub("\n", "\\n").gsub("\r", "\\r").gsub("\t", "\\t").gsub("'","\\'")  %>');

这用Javascript理解的转义序列替换了换行符。类似于其他字符,如回车和制表符。此外,它将'字符串定义字符替换为带有转义序列的字符,以便诸如It's mine之类的字符串不会引起任何意外。

This replaces the newline character with an escape sequence Javascript understands. Similarly for other characters like carriage-return and tab. Moreover it replaces the ' character which is a string delimiter character with an escape sequence for it so that a string such as "It's mine" does not cause any surprises.

这篇关于在javascript函数中插入多行字符串作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆