Home > Enterprise >  Split string by commas only not leaving whitespaces
Split string by commas only not leaving whitespaces

Time:11-07

Let's suggest I have the following string:
let cssValue = '20px, 40px'

I wish to get the following array after splitting:
cssValue.split(regex); // ['20px', '40px']

But if the string doesn't contain commas (spaces only, i.e. 20px 40px) the result should be ['20px 40px']

My regex [^a-zA-Z0-9] doesn't consider comma. With this regex I'm getting ['20px', '40px'] regardless of whether the string contains comma or not. How can I resolve it?

CodePudding user response:

You could split by comma and possible whitespace directly.

const split = s => s.split(/,\s*/);

console.log(split('20px, 40px'));
console.log(split('20px 40px'));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

If you're only intending to split-by-comma and remove leading whitespace, you won't need to use a regex at all, if you don't want to.

The string ',' will suffice, since, if you want to tidy up any leading whitespace afterwards, you can use trim().


Working Example:

let cssValue1 = '20px, 40px';
let cssValue2 = '20px 40px';

const splitCSSValue = (cssValue) => cssValue.split(',');
const trimElements = (array) => array.map((element) => element.trim());

console.log(trimElements(splitCSSValue('20px, 40px')));
console.log(trimElements(splitCSSValue('20px 40px')));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related