Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count dot in the string? [duplicate]

Tags:

javascript

I am trying to count number of dot . in the string. I am trying with match() function for counting the dot, but it does not working.

I tried same script to count other string, letter and - which is properly working. I have following string

var string = "How are you doing . - today? You . - are such a nice person!";

I tried following script

var num = string.match(/-/g).length; // output 2
var num = string.match(/are/g).length; // output 2
var num = string.match(/a/g).length; // output 4
var num = string.match(/./g).length; // output 60

Can someone guide me why it match function does not support . and how can i count it. I would like to appreciate.

like image 580
Ayaz Ali Shah Avatar asked Sep 05 '25 21:09

Ayaz Ali Shah


1 Answers

The dot . is used in regex and matches a single character, without caring which character. You need to escape the dot, like string.match(/\./g).length. The \ is the escape, and says to treat the dot as a true ., instead of the special regex meaning.

like image 60
Matt Goodrich Avatar answered Sep 08 '25 21:09

Matt Goodrich