Reputation: 1741
I have a <TextArea>
input that allows a user to enter a comma separated list, that then parses the entered values at each ,
. I'm doing this using a basic .split()
method. This obviously doesn't cover many scenarios. I also need to account for CR / LF characters (linebreaks, etc) as well as leading and trailing whitespaces.
Also a case in my instance would be; I would not want to add another set of double quotes if the values are already enclosed by them. i.e. "4456", "54456" would be treated as such and not sent as ""4456"", ""54456"".
My function that parses the entered values looks like this:
addSelectorValue = e => {
e.stopPropagation();
e.preventDefault();
this.setState(
({ selectorValues, selectorValue }) => ({
selectorValues: [...selectorValues, ...selectorValue.split(",")],
selectorValue: ""
}),
() => {
console.log("Array of selectorValues: ", this.state.selectorValues);
}
);
};
Is there a certain library or best practice, like regex, to follow to achieve the situation described above?
I have a sandbox demonstrating my use case here. If you press the submit button on the form after entering a few values, or ones wrapped in " "
, you can see the line breaks being submitted.
Upvotes: 2
Views: 1137
Reputation: 112787
You could:
/\r?\n|\r/g
with the empty string.split
the string up into an array with ,
as delimiter.trim
each substring."
with .replace(/^"(.*)"$/, "$1")
on each substring.addSelectorValue = e => {
e.stopPropagation();
e.preventDefault();
this.setState(({ selectorValues, selectorValue }) => ({
selectorValues: [
...selectorValues,
...selectorValue
.replace(/\r?\n|\r/g, "")
.split(",")
.map(str => str.trim().replace(/^"(.*)"$/, "$1"))
],
selectorValue: ""
}));
};
Upvotes: 1