photonacl
photonacl

Reputation: 135

How to detect if the first character is a carriage return, and add carriage return

I have the value of a textarea, how do I find out if the textarea starts off with a carriage return? I read some posts and understand that the CR is represented as \n? But how can I find out if the very first thing (character?) in the textarea is a return? If not, how can I add one to it?

I'm picturing something like this:

var content = $("#myTextArea").val();

if (content.charAt(0)=="\n"){
//do nothing
}
else
{
content.before("/n")
}

Apparently it's wrong but how should I do it?

Upvotes: 0

Views: 4298

Answers (2)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

I think that's what you are looking for :

var textarea = document.getElementById('myTextArea'); //Get the text area
if(textarea.value.charAt(0) !== '\n') // Check if the first char is not a newline
    textarea.value = '\n' + textarea.value; // Add a new line character.

Upvotes: 0

adeneo
adeneo

Reputation: 318182

jQuery's before inserts elements, it does not change the value of a textarea, you could do this

$("#myTextArea").val(function(_, v) {
    return (v.charAt(0) === "\n" ? "" : "\n") + v;
});

FIDDLE

Upvotes: 2

Related Questions