• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

133
Views
Split string by commas only not leaving whitespaces

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?

about 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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'));

about 3 years ago · Juan Pablo Isaza Report

0

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')));

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error