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

Answer by Ashok R for How to count string occurrence in string?

$
0
0

came across this post.

let str = 'As sly as a fox, as strong as an ox';let target = 'as'; // let's look for itlet pos = 0;while (true) {  let foundPos = str.indexOf(target, pos);  if (foundPos == -1) break;  alert( `Found at ${foundPos}` );  pos = foundPos + 1; // continue the search from the next position}

The same algorithm can be layed out shorter:

let str = "As sly as a fox, as strong as an ox";let target = "as";let pos = -1;while ((pos = str.indexOf(target, pos + 1)) != -1) {  alert( pos );}

Viewing all articles
Browse latest Browse all 43

Trending Articles



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