4

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.

4
  • 3
    Dot has a special meaning in regex, it matches with any character. Escape the dot ... string.match(/\./g).length Commented Jan 8, 2018 at 7:02
  • @gurvinder372 It is works for me thanks +1 Commented Jan 8, 2018 at 7:03
  • 1
    You can use this trick string = "How are you doing . - today? You . - are such a nice person!.";console.log(string.split('.').length); Commented Jan 8, 2018 at 7:08
  • @Mr.Developer, or use brackets like in my answer. Commented Jan 8, 2018 at 7:08

3 Answers 3

16

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.

Sign up to request clarification or add additional context in comments.

2 Comments

is it empty string safe?
Empty string, yes. If the string is null, then you'll want to check string != null first to avoid an NPE.
2

Escape the .

var string = "How are you doing . - today? You . - are such a nice person!"; var num = string.match(/\./g).length; console.log(num);

Comments

0

Dot is a special character in regex and it matches with any char.

You have to use escape the dot.

var string = "How are you doing . - today? You . - are such a nice person!"; var num = string.match(/\./g).length; // output 60 console.log(num);

Another approach is to use brackets.

var num = string.match(/[.]/g).length; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.