phantom phantom - 6 months ago 53
jQuery Question

Count number of fullstops and commas in string using regex

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>




Answer

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>