How to find count matches in string with a regexp and variable, javascript

Hello I need to get the number of matches for each character in a string and I am trying to use “for” and RegEx but my code doesn’t work because I don’t know how to use variables in RegEx

let foo = (str) => {
  for(let i=0; i< str.length; i++){
  console.log((str.match(/{HERE MUST BE str[i]}/g) || []).length);



You can create regular expressions with variables by using RegExp:

var regexp = new RegExp(str[i], 'g');

Leave a Reply

Your email address will not be published. Required fields are marked *