Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 584
jbutler483 Avatar asked Dec 08 '22 23:12

jbutler483


2 Answers

.replace() is a String method and not a jQuery method, so a simple RegExp should do.

 var text = $('.notes').html().replace(/\)\(/g, "<br/>");

Notice the g command that stands for global, which means it applies to all instances.

like image 43
thednp Avatar answered Dec 17 '22 05:12

thednp


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>
like image 160
Stewartside Avatar answered Dec 17 '22 05:12

Stewartside