用jquery替换html的格式

时间:2015-10-29 05:39:01

标签: jquery html

这是给定的格式:

how are <a href="#" class="frnd_class">Piyush</a>you fine and you <a href="#" class="frnd_class">Praveen</a>

而且,我需要通过使用jquery操作或替换html来实现以下格式:

<span>how are</span>&nbsp;<a href="#" class="frnd_class">Piyush</a>&nbsp;<span>you fine and you</span>&nbsp;<a href="#" class="frnd_class">Praveen</a>

1 个答案:

答案 0 :(得分:0)

尝试使用.contents().each().html()$.trim()String.prototype.replace()

&#13;
&#13;
$("#pred_ques").on("blur", function() {
  var div = $("<div />").html($(this).val());
  div.contents().each(function(i, el) {
    var text = el.nodeValue,
      re = /\w+/i;
    if (el.nodeType === 3 && re.test(text)) {
      div.html(function(_, html) {
        return html.replace(text, ($("span", el.parentElement).length ? "&nbsp;" : "") + $("<span />", {
          html: $.trim(text)
        })[0].outerHTML + "&nbsp;")
      });
    }
  });

  $("#pred_ques_1").val($(div)[0].innerHTML)
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" id="pred_ques" name="pred_ques" value='how are <a href="#" class="frnd_class">Piyush</a>you fine and you <a href="#" class="frnd_class">Praveen</a>'>
<input type="text" id="pred_ques_1" name="pred_ques_1" value=''>
&#13;
&#13;
&#13;

jsfiddle http://jsfiddle.net/5a9yft7h/2/