简体   繁体   中英

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()函数进行全局匹配。

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

Try this:

<!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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM