2016-04-29 25 views
0

我有一个名为变量隐藏在我的JS文件如下:如何断裂线在Javascript

var hidden=$('#hidden').val(); 

当我提醒可变隐藏,输出是

Need for voice connection\n\ with text messaging pack\n\ and 3G data 

但我需要输出为

Need for voice connection 
with text messaging pack 
and 3G data 

如何实现它?在Javascript中

+0

是你'#hidden'文本区域? –

+0

似乎*字面值*包含字符序列'\ n'。为什么和为什么它不包含真正的换行符? –

+0

@FelixKling - 这是一个HTML属性值。 – Quentin

回答

0

这个工作对我来说:

alert('test\\n\\test2\\n\\test3\\n\\test4'.replace(new RegExp(/\\n\\/g), '\n');

我更换所有excaped \n元素与非转义字符。

+0

这只替换**第一个**'\ n',并且要替换的序列总是“\ n \' 。您应该使用OP所使用的字符串对其进行测试,而不是在其中没有“\ n \'序列的字符串。 – Quentin

+0

编辑完成后,它会完全替换它的两个实例(并保留”\“ '后面)。为什么不写一些通用的? – Quentin

+0

这是@Quentin。编辑。 – tilz0R

2

所以你有一个字符串包含\n\来表示新行?

用实际的新行替换这些字符。

var data = "Need for voice connection\\n\\ with text messaging pack\\n\\ and 3G data"; 
 
alert("Original: " + data); 
 
data = data.replace(/\\n\\ /g, "\n"); 
 
alert("Replaced: " + data);

+0

@昆汀 - 完美。它的工作。JAVA中的解决方法是什么? – Satish

+0

自从2003年以来,我设法避免编写任何Java。解决方法虽然(可能取决于您对字符串做了什么*),只是使用不同的语法。 – Quentin

0

有具有文本区域没有问题,你在一些句子,换行键入,它必须作为预期的输出。这里是一个演示..

$('#viewValue').on('click', function() { 
 
    var hidden = $('#hidden').val(); 
 
    alert(hidden); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea id="hidden">Need for voice connection 
 
with text messaging pack 
 
and 3G data</textarea> 
 

 
<button id="viewValue">view</button>


如果你是从字面上键入字符\n并期待换行,那么你必须把一些额外的努力来获得所需输出。

使用正则表达式替换\n用换行符。演示如下

$('#viewValue').on('click', function() { 
 
    var hidden = $('#hidden').val().replace(/\\n/g, "\n"); 
 
    debugger; 
 
    alert(hidden); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea id="hidden">Need for voice connection \n with text messaging pack \n and 3G data</textarea> 
 

 
<button id="viewValue">view</button>