我如何使用 jQuery 查找特定字符并插入换行符?
我需要查找的字符是一个连字符 - 它始终位于电子商务网站上的产品标题中,并采用以下格式:
This is a title - This is the colour
如何找到每个产品标题的破折号并将换行符插入到单独的行中作为颜色名称?
我使用的确切 HTML 标记如下:
<a href="#" class="product c-3">
<div class="product-thumb">
<!-- Other code is in here / Removed for brevity -->
<div class="product-title">
This is a title - This is the colour
</div>
</div>
</a>
最佳答案
您可以使用 replace
找到一个 -
在元素的 HTML 中并将其替换为 -<br />
.试试这个:
$('.product-title').html(function(i, v) {
return v.replace('-', '-<br />');
});
您可以简单地替换为 '<br />'
如果您想完全删除连字符。
更新:现在可以使用箭头函数使其更加简洁:
$('.product-title').html((i, v) => v.replace('-', '-<br />'));
关于javascript - 找到一个字符并插入换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30616733/