Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
How can I split a string input in Javascript by each spacebar, but not elements inside double "quotes", single 'quotes' or backticks

I'm trying to get an array of arguments from a string by doing the following

const str = `argument "second argument" 'third argument' \`fourth argument\``;

str.split(/\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)/g);

The expected output:

['argument', '"second argument"', "'third argument'", '`fourth argument`']

But this comes out:

['argument', '`', '"second argument"', '`', "'third argument'", '`', '`fourth argument`']

How can I get back an array of just 4 elements?

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

0

After getting an array then you can use filter to filter out the unwanted string

const str = `argument "second argument" 'third argument' \`fourth argument\``;

const result = str
  .split(/\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)/g)
  .filter((s) => /[a-z]/.test(s));

console.log(result);

You can also achieve the same result using string manipulation

const str = `argument "second argument" 'third argument' \`fourth argument\``;

const replacerFn = (match) => match.split(" ").join("_");
const result = str
  .replace(/".*?"|'.*?'|`.*?`/g, replacerFn)
  .split(" ")
  .map((s) => s.split("_").join(" "));

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

I suggest that you standardized your string before split to array

Replace all ` to " and so

about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!