简体   繁体   中英

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");
}

User inputs multiple names with a line break to differentiate

name one
name two
name three

prepend and append as

Hi name one welcome to xyz
Hi name two welcome to xyz
hi name three welcome to xyz

Appending is working fine but prepend is not working as expected and it's completely ignoring the first line

You can use ES6 template literals

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');

Working Example

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM