Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split words of an input by space

I have a Laravel 9 forum project and I have added this form field:

    <div class="create__section">
       <label class="create__label BMehrBold" for="tags">Tags (separate each one by [space])</label>
       <input type="text" class="form-control BKoodakBold" id="tags" placeholder="Enter the keywords here">
       <span id="tagshow"></span>
    </div>

So as you can see I have said that Each tag should be separated by space.

So if user enters javascript for example as value, it should show this at the tagshow section:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#javascript

Then he should be able to enter other keywords as well and separate each one by [space]:

#javascript #jquery

But I need to define when the user press [space] on keyboard in order to get the tag value of the input.

So how can I do that?

>Solution :

Yep, .split() and .map() are your friends here:

const [tags, tagshow]=["tags","tagshow"].map(id=>document.getElementById(id));
tags.addEventListener("input",_=>
tagshow.textContent=tags.value.trim().split(/ +/).map(w=>"#"+w).join(" "))
<div class="create__section">
   <label class="create__label BMehrBold" for="tags">Tags (separate each one by [space])</label>
   <input type="text" class="form-control BKoodakBold" id="tags" placeholder="Enter the keywords here">
   <span id="tagshow"></span>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading