在jQuery中在最后一个文本后添加字符串

4
我正在尝试使用jquery-1.10.2构建网站,在此过程中,我希望将类似于

你期望的输出是什么? - Avinash Raj
3个回答

2

使用捕获组。

$('#divText').val($('#divText').val().replace(/(<\/?(?:style|link).*?>)/, "<!-- $1 -->"));

或者

$('#divText').val($('#divText').val().replace(/(<\/?(?:style|link)[^>]*>)/, "<!-- $1 -->"));

DEMO


如果使用非HTML 5,您可能希望添加可选的结尾空格或/。 - Bram Vanroy

1

我不太喜欢使用正则表达式来修改HTML内容,因此

$(document).ready(function() {
  $('#btnUpdate').click(function() {
    var $tmp = $('<div />', {
      html: $('#divText').val()
    });

    $tmp.find('link, style').replaceWith(function() {
      return document.createComment(this.outerHTML);
    });

    $('#divText').val($tmp.html());
  });
});

$(document).ready(function() {
  $('#btnUpdate').click(function() {
    var $tmp = $('<div />', {
      html: $('#divText').val()
    });

    $tmp.find('link, style').replaceWith(function() {
      return document.createComment(this.outerHTML);
    });

    $('#divText').val($tmp.html());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="divText" style="width: 400px; height: 300px;">
  something

  <link href="//abc.comd/ss.css" rel="stylesheet"/>

  <style>
    div: {color: red;}
  </style>

  <div>adf</div>
</textarea>
<br>
<button id="btnUpdate">Update</button>


我之前认为的目标是实际上要“删除”标签,但显然并非如此。我不知道createComment,所以这很好。+1 - Bram Vanroy

0

为什么不尝试使用removeAttr删除这些属性呢?

$(document).ready(function () {
$('#btnUpdate').click(function () {
    $('#divText').val($('#divText').removeAttr("style");
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接