I am facing an issue with extracting string values from a form input field and grouping them into separate arrays based on whether the words end in a comma or space.
My approach involved splitting the input string using commas as separators, pushing those values to the commaArray, filtering through to extract values separated by spaces, and pushing them to the spacesArray. However, I have not been successful in achieving the desired outcome. Additionally, I need to include the last word in the input field with the spaceSeparatedArray if it does not end in a comma.
To further clarify my problem, I have provided code snippets and created a StackBlitz demo - link is below.
Click here for the StackBlitz demo.
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