Quantcast
Channel: How to count string occurrence in string? - Stack Overflow
Viewing all articles
Browse latest Browse all 43

Answer by dimButTries for How to count string occurrence in string?

$
0
0

ES2020 offers a new MatchAll which might be of use in this particular context.

Here we create a new RegExp, please ensure you pass 'g' into the function.

Convert the result using Array.from and count the length, which returns 2 as per the original requestor's desired output.

let strToCheck = RegExp('is', 'g')let matchesReg = "This is a string.".matchAll(strToCheck)console.log(Array.from(matchesReg).length) // 2

Viewing all articles
Browse latest Browse all 43

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>