如何使用JQuery将<br/>标签放在内容中?

时间:2015-03-10 04:56:21

标签: jquery html replace replaceall

在我的<td>标记中,其中-.很少。我想要做的是,将<br>标记放在这个特定单词的前面。我做了replace()功能,但只更改了一个-.如何查找-.的所有实例?

原始文本

Lorem Ipsum只是印刷和排版行业的虚拟文本。 -Lorem Ipsum自16世纪以来一直是业界标准的虚拟文本。 - 它不仅存活了五个世纪,而且还延续了电子排版。

我想要什么

Lorem Ipsum只是印刷和排版行业的虚拟文本。

- 。自16世纪以来,Lorem Ipsum一直是业界标准的虚拟文本。

- 。它不仅存在了五个世纪,而且还延续了电子排版。

这是我的代码示例

<table class="Notice">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
        </tr>
    <thead>
    <tbody>
        <tr>
            <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. -.Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. -.It has survived not only five centuries, but also the leap into electronic typesetting.</td>
        </tr>
    </tbody>
</table>

的Javascript

$('td:contains("-.")').html(function (i, htm) {
    return htm.replace(/-./g, "<br>-.");
});

解决方案

我发现了我的错误 - 我没有做过每一次&#39;字。所以我使用了each()函数,它完美无缺!

$('td:contains("-.")').each(function () {
    $(this).html($(this).html().replace(/-./g, "<br>-."));
});

3 个答案:

答案 0 :(得分:2)

使用JavaScript replace()函数进行全局匹配。

replace(/-/g,"<br />-");

答案 1 :(得分:2)

试试这个:

<!DOCTYPE html>
<html>
<body>

<p>Click the button</p>

<p id="demo">Lorem Ipsum is simply dummy text of the printing and typesetting industry. -.Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. -.It has survived not only five centuries, but also the leap into electronic typesetting.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var text = document.getElementById("demo").innerHTML; 
    text = text.replace(new RegExp("-.","g"), "<br>-.");
    document.getElementById("demo").innerHTML = text ;
}
</script>

</body>
</html>

答案 2 :(得分:0)

JavaScript

<p id="changeMe"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. -.Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. -.It has survived not only five centuries, but also the leap into electronic typesetting.</p>
 <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0.min.js"></script> -->
<script>
 
 var p = document.getElementById("changeMe");
 p.innerHTML = p.innerHTML.replace(/-./g, "<br>-. ");
 </script>

相关问题