Take the 2-minute tour ×

Suppose my data is the following

Hello { "I have {g{t{" braces { between "{" { quotes{  "{{"

How can I match the { symbol that is only between the quotes? I am trying to extract the number of occurrences of a specified character only between quotes. Any ideas? The sample should match 6 braces

share|improve this question
str.match(/"(?:[^\\"]+|\\.)*"/g).join().split('{').length-1; –  adeneo Jan 25 '13 at 20:41
Why do people insist on providing answers in comments? You don't build any rep that way.... –  George Jempty Jan 25 '13 at 21:15

2 Answers 2

var nb = str.split('"').filter(function(_,i){return i%2}).join('')
     .split('{').length - 1;
share|improve this answer
What about using regular expressions? –  Mehdi Karamosly Jan 25 '13 at 20:31
+1 for .filter(function(_,i){return i%2}) :-) Oh and .split('{').length is cute as well :-) –  Jan Dvorak Jan 25 '13 at 20:33
@MehdiKaramosly regexes are like jQuery : I use them when they make the code faster, simpler or more readable. Here it's straightforward without them. –  dystroy Jan 25 '13 at 20:39

Where s is your string

s.match(/"(.+?)"/g).reduce(function(p,c) {return p + (c.match(/{/g)||[]).length;}, 0);

Since some people find regular expressions intimidating, I thought it might help to go step by step through how this works. :)

  • The first regular expression /"(.+?)"/g gives you an array of all quoted strings in the original string.
    • The starting and ending / and / are to regular expressions as quote marks are to strings. The g incidicates that this is a global search—we want all the quoted strings, not just the first one.
    • " represents a quote mark before and after the string to be matched
    • . means any character
    • +? is an idiom that means everything up to the next character in the regular expression; in other words a non-greedy match. If we used * here instead of +? we would find only one big quoted string between the very first and very last ", with all the other "s contained within it!
    • Then we put in parentheses what we want the match function to actually return to us. In this case it's everything inside the quote marks, leaving the quote marks out.
  • The second regular expression /{/g counts your { characters. By using ||[] we ensure that we get a return value of 0 even if there are no brace characters found.
  • The easiest way to sum these without needing to loop is to use reduce, which we feed an initial value of 0.
share|improve this answer

Your Answer


