我有一个字符串,我需要检查字符的出现次数
var obj = "str one,str two,str three,str four";
我正在尝试这样的事情: -
console.log(("str one,str two,str three,str four".match(new RegExp("str", "g")) || []).length);
返回4
这很好,
但我的条件是我不必检查该字符串中的 str 3 ,因此输出应为 3
帮我找到这个问题的解决方案。
谢谢
答案 0 :(得分:3)
var string = "str1,str2,str3,str4";
var count = (string.match(/str[0-24-9]/g) || []).length;
console.log(count); //3
var string = "str one,str two,str three,str four";
var count = (string.match(/str (?!three)/g) || []).length;
console.log(count); //3

(?!three) - 否定前瞻(?!)
,指定主表达式后无法匹配的组。
答案 1 :(得分:0)
将字符串拆分为数组,然后计算
元素的数量这样的东西?
var numMatches = obj.split(',').filter(function(str) {
return el !== 'str three' && el.match(/str/);
}).length
或者如果你想玩regexp,你可以使用负面的预测!
var numMatches = obj.match(/(?!str three)str/g).length;