Ideally I would like a function has_three_dots(string) to return a true or false value. The string can contain more characters but must contain exactly three dots (.), not more. They don't have to be placed together. I'm not sure whether to use regex or if there is a simpler way to do this using a vanilla js method? Thanks in advance.
What's the most efficient way of checking if a string has exactly three dots in it using JavaScript?
Asked
Active
Viewed 398 times
2 Answers
1
function has_three_dots(str) {
return str.split('.').length === 4;
}
console.log( has_three_dots('...') ); // true
console.log( has_three_dots('hello.world') ); // false
console.log( has_three_dots('hello.world.its.me') ); // true

blex
- 24,941
- 5
- 39
- 72
-
thank you, this works perfectly – BoJack Dec 06 '20 at 23:53
0
you can make a prototype on String so that you can call it on any string variable:
String.prototype.hasThreeDots = function() {
let num = 0;
for (var x = 0; x<this.length; x++) {
if (this[x] === '.') {
num += 1;
}
}
return num === 3;
}
let word = "test.word.foo."
word.hasThreeDots // true

MarketMan39
- 188
- 1
- 7