How can I put <br> tag in <td> contents with JQuery?

In my <td> tag, there are few -. in it. What I want to do is, put <br> tag in front of this specific word. I did replace() function but it changed just one -. How do I find all instances of -. ?

Original Text

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.

What I want

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.

This is my Code example

<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>-.");
});

Solution

I found my mistake - I didn't do 'every' word. So I used the each() function, and it works perfectly!

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

使用全局匹配的JavaScript替换()函数。

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

尝试这个:

<!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>
链接地址: http://www.djcxy.com/p/94034.html

上一篇: 帮助函数和原型方法来取代重型框架?

下一篇: 我如何使用JQuery将<tag>标签放在<td>内容中?