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?
5 Answers 5
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>
5 Comments
g
modifier, replace()
method converts automatically to regexp if you pass a string. Good answer, but not well explainedreplace(")(", "<br/>", "g");
. Note the last parameter, is the flags parameter. With this you gottcha now. The first parameter is an string, but replace method converts it to a regular expression. That's why if you don't put the g
flag it doesn't replace globally..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.
Comments
Here you go -
Here, /\(|\)/g
is a regex (regular expression). The flag g
means global. It causes all matches to be replaced.
$(document).ready(function() {
var text = $('.notes').text().replace(/\(|\)/g, "<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>
Comments
a answer wihtout regex (split and join):
$(function() {
var notes = $('.notes');
notes.html(notes.html().split(')(').join(')<br/>('));
});
2 Comments
)(
compared to regex?$(document).ready(function() {
$('.notes').html($('.notes').html().replace(/\)\(/g, '<br />'));
});
Comments
Explore related questions
See similar questions with these tags.