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?
4 Answers
Reset to default 6Not 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>