In the below-given sentence and I have a task is to replace or remove the underscores(“_”) from string or we can say a sentence with spaces(” “). To do this we going to use a method called replace underscores with spaces, so let’s see how to achieve this jQuery remove underscore.

Before doing jQuery remove underscore this first we will see what is use of replace() method.

What is replace() method ? – jQuery remove underscore

The replace() method search a string or a text for a defined value in a sentence, or a regular expression, and returns a result contains new string that is replaced with a defined value.

<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>contains demo</title> <script src=""></script></head><body><div class="name"> My_name </div><script>$('.name').each(function() { var $this = $(this); $this.text($this.text().replace(/_/g, ' '));});</script> </body></html>

Output : My name

In the above class name of element div ie div tag with class “name” with the help I want get result My name instead of My_name.To get this we have to remove underscore from My_name using jQuery, to do this we going to use replace() method to achieve this.To achieve this completely we can replace all underscores in a string with a space, so let’s start with this:

Below is the example form ie method called replace() we have used in the above example.

replace(/_/g, ' ');

So I have use the above replace method in jQuery. So If we need to perform the replacement afterwards, looping using each:

$('.name').each(function() { var $this = $(this); $this.text($this.text().replace(/_/g, ' '));});

As you see in the above example what jQuery is performing in which get the text value which contains the underscore ie My_Name, From this text or we can call a string it will check whether it contain underscore or not if its contain the underscore then it will going to use the method called replace in which passing the string which contain the underscore, and value passing the space.So then replace method will replacing the underscore with space in the string. And it finally it will give the output with the string not contain underscore.