Split string in JavaScript and detect line break

前端 未结 7 1172
情书的邮戳
情书的邮戳 2020-12-24 04:55

I have a small function I found that takes a string from a textarea and then puts it into a canvas element and wraps the text when the line gets to

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-24 05:05

    Use the following:

    var enteredText = document.getElementById("textArea").value;
    var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
    alert('Number of breaks: ' + numberOfLineBreaks);
    

    DEMO

    Now what I did was to split the string first using linebreaks, and then split it again like you did before. Note: you can also use jQuery combined with regex for this:

    var splitted = $('#textArea').val().split("\n");           // will split on line breaks
    

    Hope that helps you out!

提交回复
热议问题