简体   繁体   中英

How to count the amount of specifc symbols that a user has entered in a text form

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM