Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用正则表达式计算字符串中的句号和逗号数_Javascript_Jquery_Regex - Fatal编程技术网

Javascript 使用正则表达式计算字符串中的句号和逗号数

Javascript 使用正则表达式计算字符串中的句号和逗号数,javascript,jquery,regex,Javascript,Jquery,Regex,我试图用正则表达式计算句子中的句号和逗号的数量。我使用的代码如下 var commaCount = $("#text-input").val().match(new RegExp(",", "g")).length; var fullStopCount = $("#text-input").val().match(new RegExp(".", "g")).length; 这适用于逗号计数,但对于句号计数,它计算句子中的每个字符。有人能解释为什么会发生这种情况以及如何解决它吗 完整代码请参见以

我试图用正则表达式计算句子中的句号和逗号的数量。我使用的代码如下

var commaCount = $("#text-input").val().match(new RegExp(",", "g")).length;
var fullStopCount = $("#text-input").val().match(new RegExp(".", "g")).length;
这适用于逗号计数,但对于句号计数,它计算句子中的每个字符。有人能解释为什么会发生这种情况以及如何解决它吗

完整代码请参见以下内容:

var commaCount=$(“#文本输入”).val().match(新的RegExp(“,”和“g”).length;
var fullStopCount=$(“#文本输入”).val().match(新的RegExp(“.”,g”).length;
$(“.逗号计数”).text(“,:”+commaCount);
$(“.fullstop count”).text(“.:”+fullstop count)

应该只有一个句号。


您需要使用
\
转义
,因为
匹配正则表达式中除换行符以外的任何单个字符

var fullStopCount = $("#text-input").val().match(new RegExp("\\.", "g")).length;

或者像regex一样使用regex

var fullStopCount = $("#text-input").val().match(/\./g).length;

var commaCount=$(“#文本输入”).val().match(新的RegExp(“,”和“g”).length;
var fullStopCount=$(“#文本输入”).val().match(新的RegExp(“\\”,“g”).length;
$(“.逗号计数”).text(“,:”+commaCount);
$(“.fullstop count”).text(“.:”+fullstop count)

应该只有一个句号。


您需要使用
\
转义
,因为
匹配正则表达式中除换行符以外的任何单个字符

var fullStopCount = $("#text-input").val().match(new RegExp("\\.", "g")).length;

或者像regex一样使用regex

var fullStopCount = $("#text-input").val().match(/\./g).length;

var commaCount=$(“#文本输入”).val().match(新的RegExp(“,”和“g”).length;
var fullStopCount=$(“#文本输入”).val().match(新的RegExp(“\\”,“g”).length;
$(“.逗号计数”).text(“,:”+commaCount);
$(“.fullstop count”).text(“.:”+fullstop count)

应该只有一个句号。

尝试以下操作:

var fullStopCount = $("#text-input").val().match(new RegExp(/\./g)).length;
var commaCount = $("#text-input").val().match(new RegExp(/\,/g)).length;
请尝试以下内容:

var fullStopCount = $("#text-input").val().match(new RegExp(/\./g)).length;
var commaCount = $("#text-input").val().match(new RegExp(/\,/g)).length;