简体   繁体   English

在Js中用split function计算字符串中选中字母的总数

[英]Count the total number of selected alphabet in a string with split function in Js

I am trying to count the total number of p from any string in js.我正在尝试计算 js 中任何字符串中p的总数。

my js code:我的js代码:

var sp = "pappa";
var as = sp.split("p");
console.log(as.length);

But it says output: 4 in the console.但它在控制台中显示 output: 4

even I put an empty string inside sp it shows the value 1 .即使我在sp中放了一个空字符串,它也显示值1 Why It starts counting from 1 ?为什么它从1开始计数?

The output is correct. output 是正确的。 If the separator in split() occurs in first or last position of the string, then empty string is returned.如果split()中的分隔符出现在字符串的第一个或最后一个 position,则返回空字符串。 In your case, for separator 'p', str.split('p') returns an array ["", "a", "", "a"] which is of length 4.在您的情况下,对于分隔符 'p', str.split('p')返回长度为 4 的数组["", "a", "", "a"]

As java script creates at least one empty set for every split function you use so if you want to get exact count of any alphabet you need to subtract 1 from the final value.由于 java 脚本为您使用的每个拆分 function 创建至少一个空集,因此如果您想获得任何字母表的精确计数,您需要从最终值中减去 1。

as Kishor mentioned split returns an array, you can do something like this to achieve the desired behaviour:正如 Kishor 提到的 split 返回一个数组,你可以做这样的事情来实现所需的行为:

var sp = "pappa";
var as = sp.split("p");
var as2 = as.join("");
console.log(as2.length);
// number of "p"s
console.log(sp.length - as2.length);

simply put these line简单地把这些线

    var sp = "pappa";
console.log((sp.match(/p/g)).length);

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

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