简体   繁体   English

jQuery正则表达式-无法替换换行符 <br> 在img标签的title属性中

[英]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. 我写了很多包含title属性的img标签。 And I want to remove and append the title in a div tag after the img using jQuery. 我想使用jQuery在img之后删除并附加titlediv标签中。 The title contains break/new line so when jQuery appends the title to HTML, that break/new line shows a white space. title包含换行符/换行符,因此当jQuery将title附加到HTML时,换行符/换行符显示空白。

I tried servel codes with regex but I still cannot replace break/new line to <br> : 我用正则表达式尝试了服务代码,但仍然无法将break /换行替换为<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: 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. replace()方法在字符串中搜索指定的值或正则表达式,然后返回替换了指定值的新字符串。

So you will have to assign this new string to your $.title 因此,您必须将此新字符串分配给$ .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" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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