PHP's substr_count in TypeScript

Rosetta Stone: golang/Count

How to use

Install via yarn add locutus and import: import { substr_count } from 'locutus/php/strings/substr_count'.

Or with CommonJS: const { substr_count } = require('locutus/php/strings/substr_count')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1substr_count('Kevin van Zonneveld', 'e')3
2substr_count('Kevin van Zonneveld', 'K', 1)0
3substr_count('Kevin van Zonneveld', 'Z', 0, 10)false

Here's what our current TypeScript equivalent to PHP's substr_count looks like.

export function substr_count(haystack: string, needle: string, offset?: number, length?: number): number | false {
// discuss at: https://locutus.io/php/substr_count/
// original by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: Brett Zamir (https://brett-zamir.me)
// improved by: Thomas
// example 1: substr_count('Kevin van Zonneveld', 'e')
// returns 1: 3
// example 2: substr_count('Kevin van Zonneveld', 'K', 1)
// returns 2: 0
// example 3: substr_count('Kevin van Zonneveld', 'Z', 0, 10)
// returns 3: false

let cnt = 0

const normalizedHaystack = String(haystack)
const normalizedNeedle = String(needle)
const normalizedOffset = Number.isNaN(Number(offset)) ? 0 : Number(offset)
const normalizedLength = Number.isNaN(Number(length)) ? 0 : Number(length)
if (normalizedNeedle.length === 0) {
return false
}
let position = normalizedOffset - 1

while ((position = normalizedHaystack.indexOf(normalizedNeedle, position + 1)) !== -1) {
if (normalizedLength > 0 && position + normalizedNeedle.length > normalizedLength) {
return false
}
cnt++
}

return cnt
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP strings functions


Star