0

I have a form input field which I need to get the string value from and and group the inputs into separate arrays based on the weather the words end in a comma or space.

I tried taking the input string then spliting the string using comma as a separator, then pushing that to the commaArray, then filtering through that array to get values separated by spaces and pushing that to the spacesArray. I haven't had much success. I also need to group the last word in the input field with the spaces array so basically if it does not end in comma the word is grouped with the spaceSeparatedArray.

I have added code and recreated in stackblitz too - link below.

https://stackblitz.com/edit/primeng-chips-demo-ss6jy4?file=src%2Fapp%2Fapp.component.html

Input String:
"a, b, cd ef gh, ijkl, mnop"

Desired Output Arrays:
commaSeparatedArray = ["a", "b", "gh", "ijkl"]

spaceSeparatedArray = ["cd", "ef", "mnop"]

HTML

<form
[formGroup]="aForm"
(ngSubmit)="onSubmit()">

Value: {{ aForm.value | json }}

  <label>Comma Separator</label>
  
  <input
  formControlName="inputString"
  >
  <button type="submit">Submit</button>
</form>

TypeScript

import { Component } from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms'
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

    valuesArray: [];
    
    
  aForm: FormGroup;

  constructor(
    private _formBuilder: FormBuilder
  ){
    this.aForm = this._formBuilder.group({
      inputString: new FormControl()
    })

  }
  // INPUT: 
  // a, b, cd ef gh, ijkl mnop

    onSubmit() {   
      let stringIn = this.aForm.get('inputString').value;
      let commaSeparatedArray = [];
      let spaceSeparatedArray = [];

      stringIn = stringIn.split(',');
      for(let i = 0; i <= stringIn.length; i++) {
        commaSeparatedArray.push(stringIn[i]);
      }
           

      spaceSeparatedArray = commaSeparatedArray.filter(a=> a.includes(' '));

      // OUTPUT 

      console.log("SpaceSeparatedArray:  " +spaceSeparatedArray)

      console.log("CommaSeparatedArray:  " + commaSeparatedArray);
  

    }
}

Thank You

1 Answer 1

1

This should work:

const str = "a, b, cd ef gh, ijkl, mnop"

const commaSeparatedArray = str.split(' ')
.filter(s => s.slice(-1) === ',').map(s => s.replace(',', ''));

console.log(commaSeparatedArray);

const spaceSeparatedArray = str.split(' ')
.filter(s => s.slice(-1) !== ',');

console.log(spaceSeparatedArray);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.