[英]Count the number of occurrences of a character in a string in Javascript
[英]count the number of occurrences of items in a list that appear in a string in javascript
我希望能够指定一个字符/字符串列表,并找出给定字符串中列表中出现的次数。
const match = ['&', '|', '-', 'abc'];
const input = 'This & That | Or | THIS - Foo abc';
结果应该返回5
。
我可以循环匹配并使用计数器执行indexOf
,但我想知道是否有一些更简单的方法reduce
。
您可以拆分input
字符串,过滤它,然后获取长度,而不是遍历match
数组。
这是一个简单的单行:
input.split('').filter(x => match.indexOf(x) > -1).length;
片段:
const match = ['&', '|', '-']; const input = 'This & That | Or | THIS - Foo'; const count = input.split('').filter(x => match.indexOf(x) > -1).length; console.log(count); // 4
您可以使用正则表达式来查找匹配的字符:
function escape(chr) { return '\\' + chr; }
input.match(new RegExp(match.map(escape).join('|'), "g")).length
转义是必要的,以避免出现诸如|
字符问题|
在正则表达式中具有特殊含义。
由于您要求减少:
let count = Array.prototype.reduce.call(input, (counter, chr) => (counter + (match.indexOf(chr)!==-1 ? 1: 0)), 0)
更新:
根据对其他答案的评论,OP 还希望能够搜索除单个字符之外的“abc”等子字符串。 这是一个更优雅的解决方案,您可以将其放入本地模块。
有两个函数一起工作:一个转义匹配中的特殊字符,另一个进行计数。 并再次使用减少...
// This escapes characters const escapeRegExp = (str) => ( str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, "\\\\$&") ) // This returns the count const countMatches = (input, match, i = true) => ( match.reduce((c, pattern) => ( c + input.match(new RegExp(escapeRegExp(pattern), (i ? 'ig' : 'g'))).length ), 0) ) // OP's test case let match = ['&', '|', '-'], input = 'This & That | Or | THIS - Foo', count = countMatches(input, match) console.log('Expects 4: ', count, 4 === count) // Case Sensitive Test match = ['abc'] input = 'This ABC & That abc | Or | THIS - Foo' count = countMatches(input, match, false) console.log('Expects 1: ', count, 1 === count) // Case Insensitive Test count = countMatches(input, match) console.log('Expects 2: ', count, 2 === count)
您可以使用.map()
、 .filter()
和.filter()
.reduce()
链接来添加结果数组的元素
const match = ['&', '|', '-']; const input = 'This, & That | Or | THIS - Foo'; let res = match .map(v => [...input].filter(c => c === v).length) .reduce((a, b) => a + b) console.log(res);
您还可以使用for..of
循环迭代每个字符, String.prototype.contains()
,如果支持,或.some()
,以检查字符是否在连接的字符串match
。
let n = 0;
let m = match.join("");
for (let str of input) m.contains(str) && (n += 1);
for (let str of input) match.some(s => s === str) && (n += 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.