[英]How to split words of an input by space
我有一個 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
...
但是我需要定義用戶何時按下鍵盤上的 [ space ] 以獲得輸入的標簽值。
那我該怎么做呢?
是的, .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>
你可以用split()
做到這一點:
const input = "javascript html css"; const tags = input.split(' '); console.log(tags)
您可以使用String.prototype.replace()並使用模式$1
來嵌入帶有添加前綴#
的匹配項。 正則表達式/([^ ]+)/g
或/(\S+)/g
將匹配任何不是空格的內容(您的標記詞)
const el = (sel, par) => (par || document).querySelector(sel); el("#tags").addEventListener("input", () => { el("#tagshow").textContent = tags.value.replace(/([^ ]+)/g, "#$1"); });
<label> Tags (separate each one by [space]) <input type="text" id="tags" placeholder="Enter the keywords here"> </label> <div id="tagshow"></div>
上述解決方案的好處在於,您還可以很容易地將標簽包裝到SPAN
元素中作為標簽丸:
const el = (sel, par) => (par || document).querySelector(sel); el("#tags").addEventListener("input", () => { el("#tagshow").innerHTML = tags.value.replace(/(\S+)/g, `<span class="tag">#$1</span>`); });
#tagshow { display: flex; gap: 0.5rem; }.tag { background: #eee; border-radius: 0.5rem; padding: 0.3rem 0.5rem; }
<label> Tags (separate each one by [space]) <input type="text" id="tags" placeholder="Enter the keywords here"> </label> <div id="tagshow"></div>
你可以試試這個:
function splitString() { const inputTags = document.getElementById("tags").value; const tags = inputTags.toString().split(' '); console.log(tags); }
<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" style="background-color:blue; color: white; cursor:pointer;" onclick="splitString()">button</span> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.