javascript - 如何在没有提交按钮的情况下动态地在 JavaScript 文本区域中添加和附加
问题描述
app.component.html
<textarea class="form-control" rows="10" cols="40" [(ngModel)]="answer" (keyup)="onKeyUp($event)">
</textarea>
<br><br>
<textarea class="form-control" rows="10" cols="40">
{{formated}}
</textarea>
app.component.ts
answer = '';
formated: string
onKeyUp(event: any) {
this.formated = event.target.value.replace(/\/^/g, "hi");
this.formated = event.target.value.replace(/\n/g, "welcome to xyz");
}
用户输入带有换行符的多个名称以区分
name one
name two
name three
前置和附加为
Hi name one welcome to xyz
Hi name two welcome to xyz
hi name three welcome to xyz
附加工作正常,但前置没有按预期工作,它完全忽略了第一行
解决方案
您可以使用ES6 模板文字
const input = event.target.value;
// convert input to an array of non empty names
const names = input.split('\n').filter(val => val !== '');
// format the names
this.formatted = names.map(name => `Hi ${name} welcome to xyz`).join('\n');
工作示例
const handleKeyUp = () => {
const input = document.querySelector('.input').value;
// convert input to an array of non empty names
const names = input.split('\n').filter(val => val !== '');
// format the names
const formattedNames = names.map(name => `Hi ${name} welcome to xyz`).join('\n');
// display the formatted names
const output = document.querySelector('.ouput');
output.value = formattedNames;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<textarea class="input" rows="10" cols="40" onkeyup="handleKeyUp()">
</textarea>
<textarea class="ouput" rows="10" cols="40">
</textarea>
</body>
</html>
推荐阅读
- r - 在 R 数据框的 2 列中查找字符串之间的交集
- angular - Angular:在可重用/清洁方法中将 API 数据转换为新的数据类型
- c# - 使用 RTL 时带有 C# acroforms 展平问题的 IText 7
- angular - 如何在 Angular HTTPClient 中处理流
- css - Tailwind:配置配置文件后如何访问默认内容?
- java - 检测在自定义键盘(IME)Android之外按下的EditText
- c - 在C中,如何使用链表打印结构中的所有值,而这个结构是嵌套的?
- python - 当运行 yad2k 生成模型 h5 文件时,“tensorflow”在 tensorflow 2.3 中没有属性“space_to_depth”错误
- javascript - DataTables 的日期范围选择器问题
- flutter - 我无法为 Firestore 中的地图字段应用规则