简体   繁体   中英

String substitution in Javascript

Using this initialization statement:

  var str = $('#res').text();

this gives :

Details are below 1. Payables 2. Purchasing 3. Cash Management

I want to put line break <br> before each number so that the page looks like

Details are below 

1. Payables 
2. Purchasing 
3. Cash Management

I tried :

str.replace(/[^d.,]+/,'<br>');

But it is not working as expected.

You could use a regular expression and replacements

 $('#res').html(function(i, html) { return html.replace(/(\\d+)/g, '<br />$1'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="res">Details are below 1. Payables 2. Purchasing 3. Cash Management</div> 

<div id="abc">Details are below 1. Payables 2. Purchasing 3. Cash Management</div>
<div id="cd"></div>
<script>
var ab = $("#abc").text();
var cd = ab.replace(/(\d+)/g,"<br/> $1");
$("#cd").html(cd);

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