0

I can't seem to get this to work it keeps returning null. I need a very simple way to get a count of the number of quotes in a string.

var wtf = '"""'
var count = wtf.match(/"/g);
alert(count);

This has the same problem.

var count = tableitems[i].match(/\"/g);
alert(count);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Neil
  • 405
  • 2
  • 6
  • 12

3 Answers3

3

match does not return the count but the matches themselves. You want the length of your matches:

var wtf = '"""'
var matches = wtf.match(/"/g);
var count = matches ? matches.length : 0;

The last line means: "if there are matches count them, if not return zero"

Alp
  • 29,274
  • 27
  • 120
  • 198
  • is this actually a line of code? ---- var count = matches ? matches.length : 0; --- – Neil Jun 26 '13 at 23:56
  • sure, it's a ternary operator, see edit – Alp Jun 26 '13 at 23:58
  • 1
    count= matches&& matches.length || 0; also works, and is slightly faster, as is count=(matches || "").length; – dandavis Jun 27 '13 at 00:03
  • @dandavis yes, but also slightly less readable in my opinion. in the end just a matter of taste because the performance differences won't be measurable in most cases – Alp Jun 27 '13 at 00:05
2

In your first example, count is the array of matches. To see how many there are, do

alert(count ? count.length : 0) // count is null if there are no matches

In case you were thinking of making the switch (:P), coffeescript has a nice way to deal with this type of situation:

wtf = '"""'
count = wtf.match(/"/g)?.length;

If there are no matches, count will be undefined, otherwise it will be the number of matches.

Andbdrew
  • 11,788
  • 4
  • 33
  • 37
2

You could do it like that:

const countDoubleQuotes = wtf => wtf.split('"').length - 1;

console.log(countDoubleQuotes('"')); // expected 1
console.log(countDoubleQuotes('"Hello world"')); // expected 2
console.log(countDoubleQuotes('"""')); // expected 3
console.log(countDoubleQuotes('_"_')); // expected 1
Benjamin Toueg
  • 10,511
  • 7
  • 48
  • 79