如何在 html 上格式化輸入文本,示例輸入:嗨,你好
我喜歡這樣顯示輸入
'你好',
當我按回車鍵時,帶逗號的單引號將自動顯示。
有什么建議嗎?謝謝你。
uj5u.com熱心網友回復:
然后將文本格式化并回傳到輸入欄位。你只需要一個事件監聽器,一個轉換文本的函式。
const input = document.getElementById('watch');
input.addEventListener('keypress', function (e) {
e.preventDefault();
if (e.key === 'Enter') {
input.value = input.value.split(' ').map(s => `'${s}'`).toString() ',';
}
return false;
});
<form>
<input type="text" value="Hi World" id="watch">
</form>
uj5u.com熱心網友回復:
您可以使用split和join
const str = "Hi hello";
let output = '';
if(str)
output = `'${str.split(" ").join("','")}',`;
console.log(str);
uj5u.com熱心網友回復:
const string = 'a b c'
console.log(string.split(' ').map(str => `'${str}'`).toString() ',')
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/343829.html
標籤:javascript html
