给定一个包含在段落标记中的文本的.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
更新:
这是我使用$('.location-header > p').html(address);
答案 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选择器
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;
答案 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>