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

212
Views
Regex to split a string into args without breaking the quoted text

I want to take all words from a string and convert them into an array, but i don't want to break sentences that are enclosed in quotes

My code:

const content = 'this is a simple text that i "need to split into" arguments'
const args = content.split(/ +/g)
console.log(args)

// Result: ['this', 'is', 'a', 'simple', 'text', 'that', 'i', '"need', 'to', 'split', 'into"', 'arguments']

What do I need as a result:

// Result: ['this', 'is', 'a', 'simple', 'text', 'that', 'i', 'need to split into', 'arguments']
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

One simple approach would be to use string match() along with the regex pattern ".*?"|\w+. This pattern will eagerly first try to find a next doubly-quoted term. That failing, it will search for a single word. This approach avoids the possibility of consuming words which appear inside double quotes.

var content = 'this is a simple text that i "need to split into" arguments';
var matches = content.match(/".*?"|\w+/g);
for (var i=0; i < matches.length; ++i) {
    matches[i] = matches[i].replace(/^"(.*)"$/, "$1");
}
console.log(matches);

about 4 years ago · Juan Pablo Isaza Report

0

Assuming there are no escaped quotes, and the quotes are correctly paired up.

const content = 'this is a simple text that i "need to split into" arguments'
args = content.split(/\s(?=(?:[^"]*"[^"]*")*[^"]*$)/g);
console.log(args);

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!