You can use the below code to replace part of the original string based on the regex being matched. The code (I think) is self explanatory.
var regex = /(.*)#([0-9]+(?=<))(<.*)$/;
var str = '<p>Whatever #591118</p>';
var toReplace = '$1<i class="dn">$2<i>$3';
var result = str.replace(regex, toReplace);
console.log(result);
Output: <p>Whatever <i class="dn">591118<i></p>
Demo
RegEx Explanation: (for benefit of future readers)
(.*) - First capturing group ($1) which matches any number of non-newline characters (zero or more). For the above example, this would be equal to <p>Whatever.
([0-9]+(?=<)) - Second capturing group ($2) which is any string of characters starting with one numeric character (that is, 0-9) and a positive look ahead to capture all characters until a < character is encountered. For the above example, this would be equal to 591118.
(<.*) - Third capturing group ($3) which is basically all remaining characters starting with the <. For the above example, this would equal to </p>.
var str = '<p>Whatever #591118</p>';