找到一个字符并插入换行符

egr*_*103 1 html javascript css jquery

我如何使用jQuery查找特定字符并插入换行符?

我需要找到的字符是连字符 - 它始终位于电子商务网站的产品标题中,并采用以下格式:

这是一个标题 - 这是颜色

如何找到每个产品标题的短划线,并在单独的一行中插入换行符以显示颜色名称?

我正在使用的确切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>
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 6

您可以使用在元素的HTML中replace查找-并替换它-<br />.试试这个:

$('.product-title').html(function(i, v) {
    return v.replace('-', '-<br />');
});
Run Code Online (Sandbox Code Playgroud)

'<br />'如果要完全删除连字符,可以简单地替换.

示例小提琴