I am trying to add an event in a textarea to put commas after each space. As an example:
Input 1:
2 2 2 2
Output 1:
2,2,2,2 or 2, 2, 2, 2
Input 2:
2 2 2 2 2 2
Output 2:
2,2,2,2,2,2 or 2, 2, 2, 2, 2, 2
So in the frontend, I did something as follows:
<textarea
[(ngModel)]="data"
type="text"
#data
(keyup)="keyupvalue(data.value)"
></textarea>
{{ data }}
For TypeScript
as follows:
data = '';
keyupvalue(e) {
console.log(e);
this.data = e.split(' ').join(',').trim();
}
The above works fine when I've values given in the textarea like this: 2 2 2 2
Output:
2,2,2,2
I may have input like this: 2 2 2 2 2 (Two whitespaces)
Output Got:
2,2,2,2,,2
Even I may have inputs as follows:
2
2
2
2
2
2
Expected Output:
2,
2,
2,
2,
2,
2
Not sure with the above code snippet or a bit of tweak would make it work. Will appreciate if any suggestion or improvements provided.
Rather than using a simple split/trim, you may prefer to use a regular expression to capture not just a single space but group several spaces into one capture group. Then you can replace that group with a comma.
const input = `2 2 2 2
2 2 2 2 2`
const output = input.replace(/\s+/g, ', ')
console.log(output)