I have a form similar to the one in which I am writing now:
<form>
<div class="form-group">
<label for="body">Body</label>
<textarea name="body" id="body" cols="30" rows="10" class="form-control" placeholder="Your question body here"></textarea>
</div>
</form>
And i have html block which displays textarea preview:
<div class="question-preview border-top border-bottom pt-3 pb-3" id="question-preview">
<!-- <p>Default text question</p> -->
<!-- <pre class="prettyprint">var a = 5</pre> -->
</div>
How i can generate html in real time from textarea#body to div#question-preview? Comments in preview block are example of default text and code wrapping. I can't understand how recognize default text from code. I thought i can distinguish it by 4 spacing but my code not works, i'm trying something like this:
bodyTextarea.addEventListener('keyup', function (e) {
e.preventDefault();
const lines = this.value.split(/\n/);
let code = lines
.filter((line) => {
if (/\s{4}/.test(line)) {
return line;
}
})
.reduce((accumulator, current) => {
return accumulator + current;
}, '');
// FIXME
if (!/\s{4}/.test(lines[lines.length - 1])) {
if (previewQuestionArea.querySelector('p')) {
previewQuestionArea.querySelector('p').replaceWith(`<p>${lines[lines.length - 1]}</p>`);
} else {
previewQuestionArea.innerHTML = `<p>${lines[lines.length - 1]}</p>`;
}
} else {
if (code !== '') {
previewQuestionArea.innerHTML += `<pre class="prettyprint">${code}</pre>`;
}
}
});
Any ideas?
Using jQuery We can define a Regex Pattern and apply a specific styling on that code when we find a Match. In this example I'm expecting as a delimiter 3 quotes : """
For an advanced usage of syntax highliting, you better choose a library like highlight.js or Google Prettify
$('textarea').bind('keyup change', function() { var oldHtml = $(this).val(); var newHtml = oldHtml.replace(/"""(.*?)"""/g,"<span class='highlight'>$1</span>"); $(".question-preview").empty().html(newHtml); });
.highlight{ color:#B0BF1A; background-color:#000; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <div class="form-group"> <label for="mytext">Body</label> <textarea name="body" id="mytext" cols="30" rows="10" class="form-control"> </textarea> </div> </form> <div class="question-preview border-top border-bottom pt-3 pb-3" id="question-preview"> <!-- <p>Default text question</p> --> <!-- <pre class="prettyprint">var a = 5</pre> --> </div> </body>
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.