I have the following code:
<textarea type="text" placeholder="Artículo" class="articulo"></textarea>
<p class="articuloPreview"></p>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
$(".articulo").keyup(function () {
var value = $(this).val();
$(".articuloPreview").text(value);
}).keyup();
</script>
The function of this code is to show in 'real time' what you write in the textarea. What I need is that if you enclose a word or a sentence between asterisks (*) this text becomes bold . I appreciate your responses.
This is what I've tried, but it doesn't work for me:
$(".articuloPreview").text(value.replace('*', '<strong>value</strong>'));
My solution is based on replacing the text but using a regular expression (you can still improve the one that I show you to optimize what you need).
I leave you this website so you can do tests and put together a good regular expression. https://regex101.com/
Inside the expression what I suggest is to capture the group of your word or phrase and then replace and insert that captured group with
$1
(or the number of the group you need depending on the expression used) enclosed in the tag<strong></strong>
to obtain the result you need<strong>TU PALABRA O FRASE</strong>
, in this case the advantage is that the replace supports regular expressions without problems and in this case it can be used very well.I leave you an example of what my solution would be.
--- EDIT --- I want to clarify also change the method
.text
to.html
so that you can replace your text with the tags and not write directly<strong>tu texto</strong>
I hope it is useful to you!
I don't think that using replace is necessarily the best way since we don't want to replace the current string but simply if something is true then modify its appearance
You can do it this way:
keyup
input event where the user typesif
we evaluate:bold
the fontCode:
Sources
ISSUE
The problem is that an element
textarea
only allows plain text. Therefore, using atextarea
for this task is mission impossible.APPROACH TO A SOLUTION
One possible approach is to use an element with editable content , such as one
div
with the attributecontenteditable="true"
.We could then use a regular expression to capture the words delimited by '*' and replace each asterisk with an element
<strong>
and</strong>
respectively.A regular expression could be:
Now, the idea is that each element found that matches the regular expression should be replaced in such a way that the leading and trailing asterisks are replaced with the appropriate values.
For example:
Having this, we could already see an implementation of what we are trying to achieve, but we will use a button to perform the action: