简体   繁体   中英

jQuery regex - cannot replace break/new line to <br> in img tag' s title attribute

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> :

  1. $.title.replace(/\\r/, "<br />");
  2. $.title.replace(/\\n/, "<br />");
  3. $.title.replace(/\\r\\n/, "<br />");
  4. $.title.replace(/\\\\r\\\\n/, "<br />");
  5. $.title.replace(/\\\\r/, "<br />");
  6. $.title.replace(/\\\\n/, "<br />");
  7. $.title.replace(" ", "<br />");
  8. $.title.replace("&#x20;", "<br />");
  9. $.title.replace("&#x0D;&#x0A;", "<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM