通过jQuery将字符串标记转换为HTML元素

时间:2015-09-29 18:17:19

标签: jquery

我从wordpress获得的初始HTML输出:

<div class="testimonial-name">Syed Haroon {{ Web Developer_ India }}</div>

下面给出的jQuery代码会将{{转换为<span>,将}}转换为</span>,将_转换为,

jQuery('.testimonial-name').text(function(index,text){
      return text.replace("{{",'<span>')
                 .replace("}}",'</span>')
                 .replace('_',',');
    })

运行上面的代码后,结果是:

<div class="testimonial-name">Syed Haroon &lt;span&gt; Web Developer, India &lt;/span&gt;</div>

我真正需要的是:

<div class="testimonial-name">Syed Haroon <span>Web Developer, India</span></div>

2 个答案:

答案 0 :(得分:2)

使用.html()代替.text()

jQuery('.testimonial-name').html(function(index,html){
    return html.replace("{{",'<span>')
        .replace("}}",'</span>')
        .replace('_',',');
});

DEMO

答案 1 :(得分:2)

使用html()代替文字

&#13;
&#13;
jQuery('.testimonial-name').html(function(index, html) {
  return html.replace("{{", '<span>')
    .replace("}}", '</span>')
    .replace('_', ',');
})
&#13;
span{
  color:green;
  }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="testimonial-name">Syed Haroon {{ Web Developer_ India }}</div>
&#13;
&#13;
&#13;