最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - javascript - replace all white spaces with html tags to enclose remaining words - Stack Overflow

programmeradmin1浏览0评论

I have this <div>:

<div id="myDiv">
orange green, yellow
magenta/23 black: "brown"
</div>

I want to replace all white spaces with html tags to enclose remaining words,
for example (<b> tags):

<div id="myDiv">
<b>orange</b><b>green,</b><b>yellow</b>
<b>magenta/23</b><b>black:</b><b>"brown"</b>
</div>


Is there a way do to it in javascript or jquery?

I have this <div>:

<div id="myDiv">
orange green, yellow
magenta/23 black: "brown"
</div>

I want to replace all white spaces with html tags to enclose remaining words,
for example (<b> tags):

<div id="myDiv">
<b>orange</b><b>green,</b><b>yellow</b>
<b>magenta/23</b><b>black:</b><b>"brown"</b>
</div>


Is there a way do to it in javascript or jquery?

Share Improve this question asked Oct 6, 2014 at 1:48 user3542686user3542686
Add a ment  | 

4 Answers 4

Reset to default 6

Not tested, bit this should work

var myDiv = document.querySelector('#myDiv');

myDiv.innerHTML = myDiv.innerHTML.split(' ').map(function(word){
    return "<b>"+word+"</b>";
}).join('');

Another way

$('#myDiv').html(function (i, html) {
    return '<b>' + html.trim().replace(/(\s+)/g, '</b>$1<b>') + '</b>'
})

Demo: Fiddle

Simple JS approach:

var words = document.getElementById('myDiv').innerHTML.split(' ');
var output = "";
for(var i = 0; i < words.length; i++) {
    output += '<b>' + words[i] + '</b>';
}

document.getElementById('res').innerHTML = output;

See it here: http://jsfiddle/4dnp3t81/

Here my solution. I place the output inside an xmp tag so you can see the output.

var myDiv = $("#myDiv").html();
$('#output').html(myDiv.replace(/\s*(.+?)\s/g, "<b>$1</b>"));
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
orange green, yellow
magenta/23 black: "brown"
</div>
<xmp id="output"></xmp>

发布评论

评论列表(0)

  1. 暂无评论