Add Comma After Each Space

Discussão em 'Angular' iniciado por user8512043, Novembro 18, 2024.

  1. user8512043

    user8512043 Guest

    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.

    Continue reading...

Compartilhe esta Página