JavaScript 能做許多事,尤其透過瀏覽器的 API 或套件,我們得以悠游於巨量資料中,將資料轉換為與使用者溝通的介面,以下就來分享 15 個實用的 Vanilla JS 程式碼:
1. 字首大寫
const capitalizeFirstLetter = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
capitalizeFirstLetter(‘hello’); // ‘Hello’
2. 縮減字數
const truncate = (str, maxLength) => str.length > maxLength ? `${str.slice(0, maxLength)}...` : str;
truncate(`I'm telling you a long story`, 3); // I'm...
3. 取得選取文字
const getSelectedText = () => window.getSelection().toString();getSelectedText();
4. 純文字貼上
const pastePlainText = (e) => { e.preventDefault(); let text = (e.clipboardData || window.clipboardData).getData(‘text/plain’ );document.queryCommandSupported(‘insertText’)? document.execCommand(‘insertText’, false, text): document.execCommand(‘paste’, false, text);};window.onpaste = (e) => pastePlainText(e);
感謝您的閱讀,我試著將生活與自己所學到的知識,以平易近人的方式傳達給正在努力進步的同好,甚至是領域之外卻有興趣的人,您的鼓勵也是我進步的動力。