57

I have an array with objects inside of it, a few of the objects contain an underscore in the string.

Example:

{"name": "My_name"}

But I'm calling the name function in multiple places, one such place is in an image tag where the underscore is necessary, using JavaScript I want to select a certain div with the name in it and replace the underscore with space.

Example:

<div>
 <div class="name">
  My_name
 </div>
 <img src="My_name.jpg"/>
</div>

In the div.name I want it to say My name instead of My_name.

leonheess
  • 16,068
  • 14
  • 77
  • 112
PhazingAzrael
  • 721
  • 1
  • 6
  • 11
  • 1
    Does this answer your question? [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string) – leonheess Dec 24 '20 at 10:23

2 Answers2

138

You can replace all underscores in a string with a space like so:

str.replace(/_/g, ' ');

So just do that before the content is put in. If you need to perform the replacement afterwards, loop using each:

$('.name').each(function () {
    this.textContent = this.textContent.replace(/_/g, ' ');
});
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 1
    note that there are no single or double quotes for the first part written in regex – Iman Apr 24 '16 at 05:53
17

ES2021 introduced the nifty replaceAll()-function which means it can be written as:

str.replaceAll('_', ' ')

If you want to do multiple elements just loop over them and use forEach():

const elements = document.querySelectorAll('.name')   
elements.forEach(e => e.innerText = e.innerText.replaceAll('_', ' '))
leonheess
  • 16,068
  • 14
  • 77
  • 112