SyntaxError:unterminated string literal?

时间:2015-09-08 18:34:56

标签: javascript

如何计算textarea中的换行符数?

<?php
echo "<textarea value=\"\" id=\"text\" maxlength=\"200\" wrap=\"virtual\" onChange=\"test()\"></textarea>
<script>
                            function test()
                            {
                                var text = $('#text').val();   
                                var lines = text.split('\n');//SyntaxError: unterminated string literal
                                var count = lines.length;
                                console.log('+'+count); // Outputs 4
                            }
                            </script>";
?>

2 个答案:

答案 0 :(得分:2)

您需要转义\n中的反斜杠。否则,它由PHP解释,因为它在双引号字符串中,因此它成为Javascript中的文字换行符。

            var lines = text.split('\\n');

答案 1 :(得分:-1)

<textarea cols="30" id="countLines"></textarea>

var textarea = document.getElementById("countLines");
var spaces = textarea.getAttribute("cols");

textarea.onmouseout = function() {
   var lines = textarea.value.split("\n");

   for (var i = 0; i < lines.length; i++) 
   {
         if (lines[i].length <= spaces) continue;
         var j = 0;

        var space = spaces;

        while (j++ <= spaces) 
        {
           if (lines[i].charAt(j) === " ") space = j;  
        }
    lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
    lines[i] = lines[i].substring(0, space);
  }
    var count = lines.length;
};

结帐小提琴 https://jsfiddle.net/ryog4/gj5c2bkd/1/