Search code examples
javascriptjqueryhtmlreplacereplaceall

jQuery replace multiple occurrences of substring/text


I am currently trying to learn a replacemethod in jQuery.

I have a <div class="notes"> with the following text

  (1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 0 0)(1 1 1 0 0 1 1)

and would like to replace the text with certain values. For example, each time I see )(, I would want it to go to a new line (<br/>). I was attempting to use jQuery's replace method to achieve this.

 $(document).ready(function() {
    var text = $('.notes').html().replace(")(", "<br/>");
    $('.notes').html(text);
  });

I noted that when doing this, it was only replacing the first instance. So I tried a replaceAll method, although this had no effect on the string.

Quick fiddle Demo or snippet below:

$(document).ready(function() {
    var text = $('.notes').html().replace(")(", "<br/>");
    $('.notes').html(text);
    alert(text);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notes">
  (1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 0 0)(1 1 1 0 0 1 1)
</div>

Could anyone advise as to how I should go about this?


Solution

  • You need to use a regular expression instead which runs globally, notice the /g command.

    For your case, you'll need to use the following:

    /\)\(/g
    

    $(document).ready(function() {
        var text = $('.notes').html().replace(/\)\(/g, "<br/>");
        $('.notes').html(text);
      });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="notes">
      (1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 0 0)(1 1 1 0 0 1 1)
    </div>