Search code examples
javascriptstringtextreplace

How to replace part of text but not touching anything else


I'm trying to edit some text on YouTube channel pages and I want to trim off the subscribers part of the subscriber count. (E.g. 256 subscribers ----> 256). I'm a noob at programming (especially in JS) and haven't found any answers that fit what I wanted. I have a small HTML element that I want to edit with JavaScript to trim off the subscribers part and not touching the numbers. <yt-formatted-string id="subscriber-count" class="style-scope ytd-c4-tabbed-header-renderer" aria-label="2.24 million subscribers">2.24M subscribers</yt-formatted-string> And I have tried this: var get=document.getElementById('test'); var str=get.innerHTML; document.write(str.replace("Rindan's","TestNAme")); But it instead deleted the whole page and left the number in without the subscribers string so semi-success. Can anyone help me get this reliably working? Sorry for the weird formatting, the text editor for stackoverflow isn't great.


Solution

  • You can just set innerHtml of the element without writing document.

      var get=document.getElementById('subscriber-count'); 
      var str=get.innerHTML; 
      get.innerHTML = str.replaceAll("subscribers","");
    

    Something like this https://codepen.io/mikhail-vnukov/pen/QWvbeeW