[英]How to Prepend and Append in JavaScript textarea dynamically without submit button
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
前置和 append 作為
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.