How to find and count a specific word from text using JavaScript?


I have the following XML response which I converted to text:

let XMLText = '<?xml version="1.0" encoding="utf-8"?>  

now I am trying to find and count size: 4194304 from the text

I have tried using the search function but it only return the position of the string I am looking for

for example, following function returns 177, which is the position of the string"4194304") 


Using regex, this is relatively easy to do.  Make your target string a capture group by putting it in parentheses and then count how many matches it has:

let numOfOccurrences = XMLText.match(/(4194304)/).length

Answered By – Fasteroid

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published