I’m trying to insert a random length span into random places within a paragraph tag using jQuery. Think "REDACTED" text within a document.
Here’s what I’ve done so far:
$(document).ready(function() {
var xx = Math.floor(Math.random() * (14 - 4 + 1) + 4);
for (var i = 0; i < xx; i++) {
var $newsp = $('<span class="blackout"> </span>');
$("p").append($newsp);
}
});
body {
font: normal normal 400 14pt/1.15em 'Courier New', monospace;
}
.blackout {
color: #000;
background-color: #000;
}
.ins {
width: 100%;
max-width: 1400px;
margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="ins">
<p>To forgive is to set a prisoner free and discover that the prisoner was you. You gain strength, courage and confidence by every experience in which you really stop to look fear in the face. You must do the thing which you think you cannot do.</p>
<p>The unexamined life is not worth living. You gain strength, courage and confidence by every experience in which you really stop to look fear in the face. You must do the thing which you think you cannot do.</p>
<p>Nothing is a waste of time if you use the experience wisely. A man who won't die for something is not fit to live.</p>
</div>
2
Answers
Here’s a solution.
Thanks to @david for the idea.
The script starts by splitting each paragraph’s text into an array of words using the
split(" ")
method.A loop iterates through each word, and a random decision is made (with a 30% chance) whether to redact the word. If it’s chosen to be redacted, a
<span>
element with a random length of spaces is added in place of the word.After processing all words, the new content (which includes redacted words) is set as the HTML of the original paragraph using
$(this).html(newContent.trim()).
I created a jQuery plugin below that will redact words by looking for non-zero-length text nodes.
If it encounters one of these, it will:
I avoided calling
innerHTML
and$.fn.html
, and instead worked with the DOM.Note: I kept the text in the span for debugging purposes.
Here it is in action: