简体   繁体   English

如何计算用户在文本表单中输入的特定符号的数量

[英]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.抱歉,如果这似乎是一个新手问题,但我想知道是否有办法计算一个人输入的 URL 样式格式中特定符号的数量,例如点或斜线。

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 但它不起作用

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 function 我认为你可以看到/计算那里的点数

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

the if statement that I used to call the function.我曾经调用 function 的 if 语句。

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. String中任何字符的计数就是String.match(RegExp)返回的匹配数。

Since you mentioned periods specifically, and those are special RegExp symbols, you can't just write /./g for your RegExp .由于您特别提到了句点,并且这些是特殊的RegExp符号,因此您不能只为RegExp编写/./g 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.附加到末尾的g标志意味着获取所有匹配项,而不仅仅是第一个匹配项。

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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