如何在 HTML textarea 中添加换行符?
为了在 HTML textarea 中添加换行符,我们可以使用 HTML 换行标签 `
` 在需要的地方插入换行。或者,我们也可以使用 CSS 属性 `"white-space: pre-wrap"` 自动为文本添加换行符。这在 textarea 中显示预格式化文本时特别有用。因此,让我们讨论一下添加换行符的方法。
方法
在 HTML 中创建一个 textarea 并为其分配一个 id。
创建一个按钮,单击该按钮将使用换行符分割 textarea 的文本。
现在创建将文本换行的函数。此函数的代码如下:
function replacePeriodsWithLineBreaks() {
// Get the textarea element
var textarea = document.getElementById("textarea");
// Get the text from the textarea
var text = textarea.value;
// Replace periods with line breaks
text = text.replace(/\./g, "
");
// Update the textarea with the new text
textarea.value = text;
}
示例
此方法的最终代码将是:
<!DOCTYPE html>
<html>
<head>
<title>Add Line Breaks</title>
</head>
<body>
<textarea id="textarea" rows="10" cols="50"></textarea>
<br>
<button id="replace-btn" onclick="replacePeriodsWithLineBreaks()">Replace Periods with Line Breaks</button>
<script>
// Function to replace periods with line breaks in the textarea
function replacePeriodsWithLineBreaks() {
// Get the textarea element
var textarea = document.getElementById("textarea");
// Get the text from the textarea
var text = textarea.value;
// Replace periods with line breaks
text = text.replace(/\./g, "
");
// Update the textarea with the new text
textarea.value = text;
}
</script>
</body>
</html>
在这个例子中,JavaScript 代码首先使用 `getElementById()` 方法通过其 id 获取 textarea 元素。然后,它使用 `value` 属性从 textarea 获取文本。接下来,它使用 `replace()` 方法替换所有句点实例为换行符。最后,它使用 `value` 属性更新 textarea 的新文本。
注意:正则表达式 `/\./g` 中的 `g` 标志用于替换所有出现的句点。如果没有它,则只会替换第一个出现的句点。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP