How to extract words and double-quoted phrases from a string in JavaScript

2 Answers

0 votes
const str = 'This is a string with "double-quoted substring1", and "double-quoted substring2" inside.';

const result = str.match(/("[^"]+"|[^"\s]+)/g);

console.log(result);


 
/*
run:
 
[
  'This',
  'is',
  'a',
  'string',
  'with',
  '"double-quoted substring1"',
  ',',
  'and',
  '"double-quoted substring2"',
  'inside.'
]
 
*/

 



answered May 12 by avibootz
0 votes
function extractWordsAndPhrases(input) {
  // Regular expression to match words and double-quoted phrases
  const regex = /"([^"]+)"|\b\w+\b/g; 

  const matches = [];
  let match;
 
  // Use regex.exec() to find all matches
  while ((match = regex.exec(input)) !== null) {
    // If it's a quoted phrase, take the first capturing group
    matches.push(match[1] || match[0]);
  }
 
  return matches;
}
 
const str = 'This is a string with "double-quoted substring1", and "double-quoted substring2" inside.';
const result = extractWordsAndPhrases(str);
console.log(result);
 
  
  
/*
run:
  
[
  'This',
  'is',
  'a',
  'string',
  'with',
  'double-quoted substring1',
  'and',
  'double-quoted substring2',
  'inside'
]
  
*/

 



answered May 12 by avibootz
edited May 12 by avibootz
...