Reputation:
I am trying to count the number of fullstops and commas in a sentence using a regex. The code I am using is the following.
var commaCount = $("#text-input").val().match(new RegExp(",", "g")).length;
var fullStopCount = $("#text-input").val().match(new RegExp(".", "g")).length;
This works for a comma count, however for the fullstop count it counts every character in the sentence. Can anyone explain why this is happening and how to fix it.
Please see below for the complete code:
var commaCount = $("#text-input").val().match(new RegExp(",", "g")).length;
var fullStopCount = $("#text-input").val().match(new RegExp(".", "g")).length;
$(".comma-count").text(", : " + commaCount);
$(".fullstop-count").text(". : " + fullStopCount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text-input" name="textarea" rows="5" cols="50">There should only be, one full stop.</textarea>
<p class="comma-count"></p>
<p class="fullstop-count"></p>
Upvotes: 0
Views: 1613
Reputation: 1567
Try below :
var fullStopCount = $("#text-input").val().match(new RegExp(/\./g)).length;
var commaCount = $("#text-input").val().match(new RegExp(/\,/g)).length;
Upvotes: 0
Reputation: 115232
You need to escape .
using \\
, since .
matches any single character except the newline character in regex.
var fullStopCount = $("#text-input").val().match(new RegExp("\\.", "g")).length;
or use regex like
var fullStopCount = $("#text-input").val().match(/\./g).length;
var commaCount = $("#text-input").val().match(new RegExp(",", "g")).length;
var fullStopCount = $("#text-input").val().match(new RegExp("\\.", "g")).length;
$(".comma-count").text(", : " + commaCount);
$(".fullstop-count").text(". : " + fullStopCount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text-input" name="textarea" rows="5" cols="50">There should only be, one full stop.</textarea>
<p class="comma-count"></p>
<p class="fullstop-count"></p>
Upvotes: 2