0

I have a textarea. I would count lines of my input.

My simple countLines function works with all other regex, but not in this case.

function countLines(str){
  return (str.split("\r\n|\r|\n").length -1);
}

alert( countLines($("#myTextArea").html() );

Why its return is 0 even if I have multiple lines of text?

3 Answers 3

2

You are passing in a string to .split() instead of a regex. Use slashes (not quotes) to delimit your regex: /\r\n|\r|\n/.

function countLines(str){  
  return (str.split(/\r\n|\r|\n/).length -1);  
}

But, subtracting 1 from the length will only be correct if your textarea is empty. In the case that your textarea contains:

line 1
line 2

There will only be one \n. Calling .split() will return a two-item array and countLines() will return 1 when there are actually two lines, right?

Sign up to request clarification or add additional context in comments.

1 Comment

Note that .html() will not return user input, for that you have to use .val(). Here is a simple demo to show the difference between using .html() and .val() on a textarea: jsfiddle.net/YZVP6
2

Don't use split. Here's an even better way since you'll probably be working with a DOM element. The example below counts the lines of code in a "pre" element. Substitute "pre" for any selector desired. Enjoy.

var count = $('pre').text().match(/\r?\n|\r/mg).length;

Comments

1

You probally want the regex form.

function countLines(str){
   return (str.split(/\r?\n|\r/).length);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.