gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:37:01 25 4
gpt4 key购买 nike

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

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;

$(".comma-count").text(", : " + commaCount);
$(".fullstop-count").text(". : " + fullStopCount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text-input" name="textarea" rows="5" cols="50">There should only be, one full stop.</textarea>

<p class="comma-count"></p>
<p class="fullstop-count"></p>

最佳答案

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

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

或使用正则表达式,例如

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

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

$(".comma-count").text(", : " + commaCount);
$(".fullstop-count").text(". : " + fullStopCount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text-input" name="textarea" rows="5" cols="50">There should only be, one full stop.</textarea>

<p class="comma-count"></p>
<p class="fullstop-count"></p>

关于javascript - 使用正则表达式计算字符串中句号和逗号的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37372900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com