Match the number of characters between quotes with Javascript?
Suppose my data is as follows
Hello { "I have {g{t{" braces { between "{" { quotes{ "{{"
How can I match a {character that is only between quotes? I am trying to extract the number of occurrences of a specified character only between quotes. Any ideas? The sample must match 6 figures
+3
source to share
2 answers
Where s
is your string
s.match(/"(.+?)"/g).reduce(function(p,c) {return p + (c.match(/{/g)||[]).length;}, 0);
Since some people find regexes intimidating, I thought it might help step by step how it works. :)
- The first regex
/"(.+?)"/g
gives you an array of all quoted strings in the original string.- Beginning and trailing
/
and/
refer to regular expressions, as quotation marks refer to strings.g
rules out that this is a global search - we want all quoted strings, not just the first one. -
"
represents the quotation mark before and after the string to be matched -
.
means any character -
+?
is an idiom that means everything up to the next character in a regular expression; in other words, not a greedy match. If we used*
instead here+?
, we could only find one big quoted string between the very first and the very last"
, with everything else"
contained in it! - We then put in parentheses what we want the match function to actually return to us. In this case, everything is inside the quotation marks, leaving the quotation marks.
- Beginning and trailing
- The second regex will
/{/g
count your characters{
. By using||[]
, we ensure that we get the return value0
even if no parentheses were found. - The easiest way to sum them up without having to use a loop is to use
reduce
which we are passing the initial value0
.
0
source to share