简体   繁体   English

如何检测第一个字符是否为回车符,并添加回车符

[英]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? 我有textarea的值,如何确定textarea是否以回车开头? I read some posts and understand that the CR is represented as \\n? 我阅读了一些帖子,并了解到CR表示为\\ 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 jQuery的before插入元素,它不会更改textarea的值,您可以执行此操作

$("#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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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