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
  • 756,363
  • 169
  • 1,062
  • 1,111
Neil
  • 395
  • 2
  • 5
  • 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
  • 28,390
  • 26
  • 114
  • 195
  • 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,468
  • 3
  • 32
  • 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
  • 9,863
  • 7
  • 44
  • 73