用JS变量中的值替换div中的文本

时间:2017-03-06 18:36:57

标签: javascript jquery

给定一个包含在段落标记中的文本的.location-header类,我需要将存储在div中的当前值替换为address变量中存储的值。我可以替换该值,但问题是让它保持在<p></p>标记内以进行格式化。

var fixed = $('.location-header > p')[0].innerHTML
                              .replace('/(,)(?=\s{1}\D{2}[^\s][^\d{5,}])/g', "<br />");
var address = fixed.substring(0, fixed.lastIndexOf(',')).replace(/,/g, "<br />");

console.log(address);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="location-header">
  <p>
    123 Nowhere Ln, Suite 200, Somewhere, NY 10009
  </p>
</div>

它需要使用包含HTML <br />标记的文本替换纯文本。我尝试过使用.text.innerHTML.replaceWith

最终结果应该显示如下地址:

  

123无处Ln

     

Suite 200

     

某处,NY 10009

Fiddle

更新:

这是我使用$('.location-header > p').html(address);

时得到的结果

enter image description here

3 个答案:

答案 0 :(得分:1)

您可以使用jQuery .html()函数执行此操作:

var fixed = $('.location-header > p')[0].innerHTML.replace('/(,)( =\s{1}\D{2}[^\s][^\d{5,}])/g', "<br />");
var address = fixed.substring(0, fixed.lastIndexOf(',')).replace(/,/g, "<br />");

console.log(address);

$('.location-header > p').html(address);

答案 1 :(得分:1)

使用:first-child css选择器

&#13;
&#13;
                 
var fixed = " street name, area, city, pin:000000";
var address = fixed.substring(0, fixed.lastIndexOf(',')).replace(/,/g, "<br />");
var fixed = $('.location-header > p:first-child').html(address.replace('/(,)(?=\s{1}\D{2}[^\s][^\d{5,}])/g', "<br />"));
console.log(address);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="location-header">
  <p>
    123 Nowhere Ln, Suite 200, Somewhere, NY 10009
  </p>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您应该使用以下html()方法。

var fixed = $('.location-header > p').text();

var address = fixed.substring(0, fixed.lastIndexOf(',')).replace(/,/g, "<br />") + fixed.substring(fixed.lastIndexOf(','));

$('.location-header > p').html(address);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="location-header">
    <p>
        123 Nowhere Ln, Suite 200, Somewhere, NY 10009
    </p>
</div>