Javascript中的字符串替换

时间:2016-01-18 05:08:54

标签: javascript

使用此初始化语句:

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

这给出了:

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

我想在每个数字前加上换行符<br>,以便页面看起来像

Details are below 

1. Payables 
2. Purchasing 
3. Cash Management

我试过了:

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

但它没有按预期工作。

2 个答案:

答案 0 :(得分:2)

您可以使用正则表达式和替换

$('#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>

答案 1 :(得分:1)

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