17 October 2024

You can count the asterisks at the end of a string, in JavaScript, using this snippet. This uses match() with the regex \*+$ to find the sequence of asterisks at the end of the string. If there's a match, it returns the length of that sequence; otherwise, it returns 0.

Source code viewer
  1. function countAsterisksFromEnd(str) {
  2. const match = str.match(/\*+$/);
  3. return match ? match[0].length : 0;
  4. }
  5.  
  6. const result = countAsterisksFromEnd("Hello****"); // Returns 4
  7. console.log(result);
Programming Language: Javascript