简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM