I am currently trying to learn a replace
method 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?
.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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With