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

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

本文关键字:回车 添加 是否 字符 何检测 检测 第一个      更新时间:2023-09-26

我有一个文本区域的值,如何确定文本区域是否以回车符开头?我阅读了一些帖子并了解 CR 表示为 '?但是我怎么知道文本区域中的第一件事(字符?)是否是返回?如果没有,我该如何添加一个?

我正在想象这样的东西:

var content = $("#myTextArea").val();
if (content.charAt(0)=="'n"){
//do nothing
}
else
{
content.before("/n")
}

显然这是错误的,但我应该怎么做?

jQuery的before插入元素,它不会改变文本区域的值,你可以这样做

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

小提琴

我认为这就是你要找的:

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.