-1

I want to filter out text which is not inside the quotation marks.

This is my code example

var string = "text here should be ignored 'text here matters' ignore this 'this matters!'";
var matches = string.match(/'(.*)'/);

console.log(matches);

Current result

[
  "'text here matters' ignore this 'this matters!'",
  "text here matters' ignore this 'this matters!"
]

Expected result

[
  "text here matters", 
  "this matters!"
]
Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68
Xenen
  • 9
  • 4

2 Answers2

0
const input = "'text here matters' ignore this 'this matters!'";
const regex = /(?:')([^']*)(?:')/g;

const results = [];
while (match = regex.exec(input)) {
  results.push(match[1]);
}

console.log(results);

or

const input = "'text here matters' ignore this 'this matters!'";
const regex = /(?:')([^']*)(?:')/g;

const matches = [...input.matchAll(regex)];
const results = matches.map(m => m[1]);

console.log(results);
neaumusic
  • 10,027
  • 9
  • 55
  • 83
0

I googled for "JavaScript regexp findall" and found that there is a method called matchAll. This is exactly what you need.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll

You need to replace the .* in your regular expression with .*? to make it "non-greedy". At least in Perl and Java this works.

And if it doesn't, change the regular expression from "quote, anything, quote" to "quote, non-quotes, quote", which is '[^']*'.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121