如何在Angular输入中保留换行符

时间:2016-03-30 20:30:33

标签: javascript angularjs json

我注意到了一种我不想要的行为。我有一个<textarea>,如果我可以输入一些文字,如下所示。

some content
some other content 
yet another content

当我将此文本保存到JSON对象并存储它时,我得到的是:

 "value" : "some content some other content yet another content"

或者,我有时会得到这个:

"value" : "some content
some other content      
yet another content"

我猜我期待接收的内容是:

"value" : "some content \n
    some other content \n     
    yet another content"

这样我就能以与输入内容相同的方式呈现内容。

但这似乎打破了我的JSON.parse(string)。 我在 AngluarJS 中使用输入中的模型。

修改

如果我将我的Object放在JSON验证器中会发生这种情况: enter image description here

3 个答案:

答案 0 :(得分:1)

您可以尝试用其他内容替换换行符。 如果换行符会导致JSON.parse出现问题,请尝试将其替换为<br/>之类的其他内容,以便在检索数据时将其作为换行符。

在使用JSON.stringify之前,您还可以尝试使用textarea JSON.parsetextareadocument.getElementById("textarea-id").value.replace(/\n\r?/g, '<br />') 值转换为带有可见换行符的JSON字符串。

JSON.stringify(document.getElementById("textarea-id").value)

console.log

请参阅以下示例中的depends 'golang_app'https://jsfiddle.net/fjj2psqj/1/

答案 1 :(得分:0)

// valid JSON
var data = {
    "value": [
      "line",
      "line",
      "line"
    ]
};

// stringify the data to save it as text
var dataString = JSON.stringify(data);

// parse the string and join the array to recover line breaks
// or iterate over values array depending on your use case
var withNewLines = JSON.parse(dataString).value.join("\n");

答案 2 :(得分:0)

您可以先将捕获的textarea字符串通过JSON.stringify运行,然后再将其发送到您的服务器,然后再在您的应用程序中再次使用JSON.parse。

$scope.doSomethingWithTextareaText = function() {
    //assuming your textarea is bound to $scope.text
    $scope.myObject['value'] = $scope.text;
    $scope.myObject['stringifyValue'] = JSON.stringify($scope.text);
    /*
      $scope.myObject[value]: 
        some content
        some other content 
        yet another content
      $scope.myObject[stringifyValue]: 
        "some content\nsome other content\nyet another content"
      JSON.parse($scope.myObject[stringifyValue]): 
        some content
        some other content 
        yet another content
    */
}

请参阅http://jsfiddle.net/5d2oekv0/3/