I wrote a lot of img
tags containing title
attribute. And I want to remove and append the title
in a div
tag after the img
using jQuery. The title
contains break/new line so when jQuery appends the title
to HTML, that break/new line shows a white space.
I tried servel codes with regex but I still cannot replace break/new line to <br>
:
$.title.replace(/\\r/, "<br />");
$.title.replace(/\\n/, "<br />");
$.title.replace(/\\r\\n/, "<br />");
$.title.replace(/\\\\r\\\\n/, "<br />");
$.title.replace(/\\\\r/, "<br />");
$.title.replace(/\\\\n/, "<br />");
$.title.replace(" ", "<br />");
$.title.replace(" ", "<br />");
$.title.replace("
", "<br />");
jsfiddle:
$.title = $(".abc").attr('title'); alert($.title); //not working $.title.replace(/\\r\\n/, "<br />"); alert($.title); $(".abc").after("<div>" + $.title + "</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img class="abc" title="abc def" />
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
So you will have to assign this new string to your $.title
Try like this.
$.title = $(".abc").attr('title'); alert($.title); //working $.title = $.title.replace(/(\\r\\n|\\n|\\r)/gm,"<br />"); alert($.title); $(".abc").after("<div>" + $.title + "</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img class="abc" title="abc def" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.