I’m trying to create an array of strings in JS
on input change in React. This is all working fine. The end goal is to have a comma and space separated list of keywords in the input that has no special characters. Special characters including space need to be removed and replaced with -
. I have the input working all is good except two scenarios. If the user doesn’t enter a space after the comma the word doesn’t separate. And a trailing -
is left if a special character or space is entered. I want to then split input into array using .split(', ')
to create an array of keywords. Is it better to do regex and then split?
Currently using
mods = mods.split(', ');
const formatted = mods.map(mod => {
return mod.replace(/[^,A-Z0-9]+/ig, "-").toLowerCase();
});
example input/output
in = hello world&,anotHer, test8(
out = hello-world, another, test8