Ninjas and Monkeys and Bears, Oh My!
JavaScript ES6, 86 bytes

f=s=&gt;'NBM BM NB M B N'.replace(/\S+/g,e=&gt;(i=0,s=s.replace(RegExp(e,'g'),_=&gt;++i))&amp;&amp;i+e)


(I just had to answer this.) It goes through each substring of NBM, starting with the longer ones, which take higher priority. It searches for each occurrence of that particular string and removes it (in this case replacing it with the current count so it won't be matched again). It finally replaces each substring with the count + the string.

This Stack Snippet is written in the ES5 equivalent of the above code to make it easier to test from any browser. It is also slightly ungolfed code. The UI updates with every keystroke.



f=function(s){
  return'NBM BM NB M B N'.replace(/\S+/g,function(e){
    i=0
    s=s.replace(RegExp(e,'g'),function(){
      return++i
    })
    return i+e
  })
}

run=function(){document.getElementById('output').innerHTML=f(document.getElementById('input').value)};document.getElementById('input').onkeyup=run;run()
&lt;input type="text" id="input" value="NBMMBNBNBM" /&gt;&lt;br /&gt;&lt;samp id="output"&gt;&lt;/samp&gt;