【问题标题】:How to split words of an input by space如何按空格拆分输入的单词
【发布时间】:2022-12-31 17:05:03
【问题描述】:
我有一个 Laravel 9 论坛项目,我添加了这个表单字段:
<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>
正如你所看到的,我说过每个标签都应该用空间.
因此,如果用户输入 javascript 作为值,它应该在 tagshow 部分显示:
#javascript
然后他也应该能够输入其他关键字,并用 [空间]:
#javascript #jquery...
但我需要定义用户何时按下 [空间] 在键盘上,以获得输入的标签值。
那我该怎么做呢?
【问题讨论】:
标签:
javascript
jquery
laravel
laravel-9
【解决方案1】:
你可以用split()来做:
const input = "javascript html css";
const tags = input.split(' ');
console.log(tags)
【解决方案2】:
是的,.split() 和 .map() 是你的朋友:
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>