首页 > 解决方案 > 如何在没有提交按钮的情况下动态地在 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

附加工作正常,但前置没有按预期工作,它完全忽略了第一行

标签: javascriptangular

解决方案


您可以使用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>


推荐阅读