1

Sorry if it seems like a newbie question but I was wondering if there was a way to count the amount of specific symbols like a dot or slash in a URL style format that a person has entered.

var regex = /https?:\/\/(www\.)?[A-Za-z=:.]{1,12}\.[A-Za-z]{1,6}\b([-A-Za-z0-9%_\+=?&//#]){1,250}/
var validx = regex.test(document.getElementById("webname").value);

That's the regex and how Im calling the text input. So from that I was wondering if there was a way of counting the amount of symbols a user has entered.

I thought I could just call the function that contained a checker but it does not work

function dotcheck()
{
   var dots = detect.webname.value;
   if (dots.indexOf(".") > 0){}

the function where I thought you could see/count the amount of dots there

if (dotcheck = false){
            messages.innerHTML = 'Safe';

the if statement that I used to call the function.

Any help would be appreciated and if there is anything else you would need from me don't hesitate in asking.

  • Are you looking to detect the presence of a specific symbol, or are you looking to see how many times a certain symbol occurs? – Rodentman87 May 25 '20 at 18:20
  • looking to see how many times the symbol occurs –  May 25 '20 at 18:43
  • 1
    Does this answer your question? [Count the number of occurrences of a character in a string in Javascript](https://stackoverflow.com/questions/881085/count-the-number-of-occurrences-of-a-character-in-a-string-in-javascript) – Rodentman87 May 25 '20 at 18:48
  • I will try it out thank you –  May 25 '20 at 19:05

1 Answers1

0

The count of any character in a String is simply how many matches String.match(RegExp) returns.

Since you mentioned periods specifically, and those are special RegExp symbols, you can't just write /./g for your RegExp. You have to escape it with a \, like this:

/\./g

The g flag appended to the end means get all matches, not just the first one.

const string = 'https://stackoverflow.com/questions/62008355';
const slashes = /\//g;
const count = string.match(slashes).length;
console.log(count); // 4 slashes

const string = 'https://stackoverflow.com/questions/62008355';
const periods = /\./g;
const count = string.match(periods).length;
console.log(count); // 1 period
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43