Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading