├── debug.log ├── package.json ├── README.md └── index.js /debug.log: -------------------------------------------------------------------------------- 1 | [0401/185104.829:ERROR:crashpad_client_win.cc(811)] not connected 2 | [0401/185105.009:ERROR:crashpad_client_win.cc(811)] not connected 3 | [0401/195325.553:ERROR:crashpad_client_win.cc(811)] not connected 4 | [0401/195325.679:ERROR:crashpad_client_win.cc(811)] not connected 5 | [0401/202510.740:ERROR:crashpad_client_win.cc(811)] not connected 6 | [0401/202510.971:ERROR:crashpad_client_win.cc(811)] not connected 7 | [0403/213703.546:ERROR:crashpad_client_win.cc(811)] not connected 8 | [0403/213703.668:ERROR:crashpad_client_win.cc(811)] not connected 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@navin0507/string-utilsmns", 3 | "version": "1.0.7", 4 | "description": "Get the string utility functions to reduce rewriting code", 5 | "keywords": [ 6 | "stringutils" 7 | ], 8 | "homepage": "https://github.com/NAVIN0507/getStringUtils#readme", 9 | "bugs": { 10 | "url": "https://github.com/NAVIN0507/getStringUtils/issues" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/NAVIN0507/getStringUtils.git" 15 | }, 16 | "license": "ISC", 17 | "author": "navin mns", 18 | "type": "commonjs", 19 | "main": "index.js", 20 | "scripts": { 21 | "test": "echo \"Error: no test specified\" && exit 1" 22 | }, 23 | "dependencies": { 24 | "string-utilsmns": "^1.0.1" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 📜 String Utilities - @navin0507/string-utilsmns 2 | 3 | A lightweight and powerful **string utility package** for JavaScript & TypeScript. It provides essential string manipulation functions for **web development** and **general programming**. 4 | 5 | ## 🚀 Features 6 | ✔ Extract initials from a string 7 | ✔ Convert strings to different cases (kebab-case, PascalCase, snake_case) 8 | ✔ Generate random strings and slugs 9 | ✔ Sanitize HTML & validate URLs 10 | ✔ Encode/decode URLs & handle query strings 11 | ✔ Format and transform text easily 12 | 13 | --- 14 | 15 | ## 📦 Installation 16 | Install via **npm**: 17 | ```sh 18 | npm install @navin0507/string-utilsmns 19 | ``` 20 | or via **yarn**: 21 | ```sh 22 | yarn add @navin0507/string-utilsmns 23 | ``` 24 | 25 | --- 26 | 27 | ## 🚀 Usage 28 | Import functions in your **JavaScript** or **TypeScript** project: 29 | ```js 30 | const { getInitials, toKebaCase, isValidEmail } = require('@navin0507/string-utilsmns'); 31 | 32 | // Extract initials 33 | console.log(getInitials("John Doe", 2)); // Output: JD 34 | 35 | // Convert to kebab-case 36 | console.log(toKebaCase("Hello World")); // Output: hello-world 37 | 38 | // Validate Email 39 | console.log(isValidEmail("test@example.com")); // Output: true 40 | ``` 41 | 42 | --- 43 | 44 | ## 📚 Functions & Use Cases 45 | 46 | | **Function** | **Description** | **Example Usage** | 47 | |-------------|----------------|--------------------| 48 | | `getInitials(str, length)` | Extracts initials from a name | `getInitials("John Doe", 2)` → `"JD"` | 49 | | `getRandomString(length)` | Generates a random alphanumeric string | `getRandomString(8)` → `"aB9xT3pL"` | 50 | | `toKebaCase(str)` | Converts string to kebab-case | `toKebaCase("Hello World")` → `"hello-world"` | 51 | | `toSnakeCase(str)` | Converts string to snake_case | `toSnakeCase("Hello World")` → `"hello_world"` | 52 | | `toPascalCase(str)` | Converts string to PascalCase | `toPascalCase("hello world")` → `"HelloWorld"` | 53 | | `truncateString(str, length)` | Truncates string with `...` | `truncateString("Hello World", 5)` → `"Hello..."` | 54 | | `removeWhitespace(str)` | Removes all whitespace from string | `removeWhitespace("Hello World")` → `"HelloWorld"` | 55 | | `toTitleCase(str)` | Converts to Title Case | `toTitleCase("hello world")` → `"Hello World"` | 56 | | `toSlug(str)` | Converts string to a slug | `toSlug("Hello World!")` → `"hello-world"` | 57 | | `maskString(str, visibleCount, maskChar)` | Masks a string (e.g., credit card, email) | `maskString("12345678", 4, "*")` → `"****5678"` | 58 | | `handleURL(str, type)` | Encodes or decodes a URL | `handleURL("Hello World!", "encode")` → `"Hello%20World%21"` | 59 | | `sanitizeHTML(str)` | Escapes HTML to prevent XSS attacks | `sanitizeHTML('')` → `"<script>alert("XSS")</script>"` | 60 | | `getDomain(url)` | Extracts domain from a URL | `getDomain("https://example.com/page")` → `"example.com"` | 61 | | `isValidEmail(email)` | Validates email format | `isValidEmail("test@example.com")` → `true` | 62 | | `parseQueryString(query)` | Converts query string to an object | `parseQueryString("name=John&age=25")` → `{ name: "John", age: "25" }` | 63 | | `toQueryString(params)` | Converts an object to a query string | `toQueryString({ name: "John", age: 25 })` → `"name=John&age=25"` | 64 | | `stripHTML(str)` | Removes all HTML tags | `stripHTML("

Hello

")` → `"Hello"` | 65 | | `isValidURL(str)` | Checks if a string is a valid URL | `isValidURL("https://google.com")` → `true` | 66 | | `normalizeURL(url)` | Ensures URL has `http://` or `https://` | `normalizeURL("google.com")` → `"https://google.com"` | 67 | | `obfuscateEmail(email)` | Hides email partially for privacy | `obfuscateEmail("test@example.com")` → `"****@example.com"` | 68 | | `getRandomHexColor()` | Generates a random hex color | `getRandomHexColor()` → `"#a3f4c9"` | 69 | | `rgbToHex(r, g, b)` | Converts RGB to HEX color | `rgbToHex(255, 0, 0)` → `"#ff0000"` | 70 | | `hexToRgb(hex)` | Converts HEX to RGB color | `hexToRgb("#ff0000")` → `"rgb(255, 0, 0)"` | 71 | | `isJSON(str)` | Checks if a string is valid JSON | `isJSON('{"name":"John"}')` → `true` | 72 | | `addOrdinalSuffix(num)` | Adds ordinal suffix to a number | `addOrdinalSuffix(21)` → `"21st"` | 73 | | `markdownToHTML(markdown)` | Converts basic markdown to HTML | `markdownToHTML("**Bold**")` → `"Bold"` | 74 | 75 | --- 76 | 77 | ## 🛠️ Contributing 78 | Want to contribute? Awesome! 🎉 79 | Follow these steps: 80 | 1. **Fork** the repository 81 | 2. **Clone** your fork: 82 | ```sh 83 | git clone https://github.com/NAVIN0507/getStringUtils.git 84 | ``` 85 | 3. **Create a branch**: 86 | ```sh 87 | git checkout -b feature-new-function 88 | ``` 89 | 4. **Make your changes** & **commit**: 90 | ```sh 91 | git commit -m "Added new string utility function" 92 | ``` 93 | 5. **Push & Create a PR**: 94 | ```sh 95 | git push origin feature-new-function 96 | ``` 97 | Open a Pull Request (PR) on GitHub 🚀 98 | 99 | --- 100 | 101 | ## 📜 License 102 | This package is licensed under the **ISC License**. 103 | You are free to use, modify, and distribute it **with attribution**. 104 | 105 | ``` 106 | ISC License 107 | 108 | Permission to use, copy, modify, and/or distribute this software for any purpose 109 | with or without fee is hereby granted, provided that the above copyright notice 110 | and this permission notice appear in all copies. 111 | 112 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 113 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 114 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 115 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 116 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 117 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 118 | SOFTWARE. 119 | ``` 120 | 121 | --- 122 | 123 | ### **📢 Enjoy coding! If you like this package, don't forget to ⭐ it on GitHub!** 🚀 124 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @param {string} word 4 | * @param {number} length 5 | * @param {string} str 6 | * @returns {string} 7 | */ 8 | function getInitials(word, length) { 9 | return word 10 | .split(/\s+/) 11 | .filter((part) => part.length > 0) 12 | .map((part) => part[0].toUpperCase()) 13 | .join("") 14 | .slice(0, length); 15 | } 16 | 17 | function getRandomString(length){ 18 | const characters = 19 | "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 20 | let string = ""; 21 | for(let i =0;i Hello_world 34 | return str.replace(/\s+/g, "_").toLowerCase(); 35 | } 36 | //Convert the String into Pascal Case 37 | function toPascalCase(str) { //helloworld --> HelloWorld 38 | return str 39 | .replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => word.toUpperCase()) 40 | .replace(/\s+/g, ""); 41 | } 42 | 43 | //Truncate String 44 | function truncateString(str, length) { 45 | //Hello World 2 --> He.......... 46 | return str.length > length ? str.slice(0, length) + "..." : str; 47 | } 48 | 49 | //Remove White Space 50 | function removeWhitespace(str) { 51 | //Hello World --> HelloWorld 52 | return str.replace(/\s+/g, ""); 53 | } 54 | //Convert String to Title Case 55 | function toTitleCase(str) { 56 | return str.replace( 57 | /\w\S*/g, 58 | (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() 59 | ); 60 | } 61 | //Generate a Slug from a String 62 | function toSlug(str) { 63 | return str 64 | .toLowerCase() 65 | .trim() 66 | .replace(/\s+/g, "-") 67 | .replace(/[^\w-]/g, ""); 68 | } 69 | //Mask a String (e.g., Credit Card, Email) 70 | function maskString(str, visibleCount = 4, maskChar = "*") { 71 | return maskChar.repeat(str.length - visibleCount) + str.slice(-visibleCount); 72 | } 73 | //Encode & Decode URL Components 74 | function handleURL(str, type = "encode") { 75 | return type === "encode" ? encodeURIComponent(str) : decodeURIComponent(str); 76 | } 77 | //Sanitize HTML (Prevent XSS) 78 | function sanitizeHTML(str) { 79 | return str 80 | .replace(/&/g, "&") 81 | .replace(//g, ">") 83 | .replace(/"/g, """) 84 | .replace(/'/g, "'"); 85 | } 86 | //Extract Domain from URL 87 | function getDomain(url) { 88 | try { 89 | return new URL(url).hostname; 90 | } catch { 91 | return null; 92 | } 93 | } 94 | //Validate Email Format 95 | function isValidEmail(email) { 96 | return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); 97 | } 98 | //Convert Query String to Object ✅ 99 | function parseQueryString(query) { 100 | return Object.fromEntries(new URLSearchParams(query)); 101 | } 102 | //Convert Object to Query String 103 | function toQueryString(params) { 104 | return new URLSearchParams(params).toString(); 105 | } 106 | //Strip HTML Tags 107 | function stripHTML(str) { 108 | return str.replace(/<[^>]*>?/gm, ""); 109 | } 110 | //Check if String is a Valid URL 111 | function isValidURL(str) { 112 | try { 113 | new URL(str); 114 | return true; 115 | } catch { 116 | return false; 117 | } 118 | } 119 | // Normalize URL (Ensure HTTP/HTTPS) 120 | function normalizeURL(url) { 121 | if (!/^https?:\/\//i.test(url)) { 122 | return `https://${url}`; 123 | } 124 | return url; 125 | } 126 | //Obfuscate Email (For Privacy Protection) 127 | function obfuscateEmail(email) { 128 | return email.replace(/(.)(?=.*@)/g, "*"); 129 | } 130 | //Generate Random Hex Color 131 | function getRandomHexColor() { 132 | return `#${Math.floor(Math.random() * 16777215).toString(16)}`; 133 | } 134 | 135 | // Extract Meta Tags from HTML 136 | function getMetaTagContent(html, metaName) { 137 | const regex = new RegExp( 138 | `]+name=["']${metaName}["'][^>]+content=["']([^"']+)["']`, 139 | "i" 140 | ); 141 | const match = html.match(regex); 142 | return match ? match[1] : null; 143 | } 144 | //Convert RGB to HEX 145 | function rgbToHex(r, g, b) { 146 | return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`; 147 | } 148 | //Convert HEX to RGB 149 | function hexToRgb(hex) { 150 | const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); 151 | return result 152 | ? `rgb(${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt( 153 | result[3], 154 | 16 155 | )})` 156 | : null; 157 | } 158 | //Detect if a String is a JSON 159 | function isJSON(str) { 160 | try { 161 | JSON.parse(str); 162 | return true; 163 | } catch { 164 | return false; 165 | } 166 | } 167 | //Add Ordinal Suffix to a Number 168 | function addOrdinalSuffix(num) { 169 | const suffixes = ["th", "st", "nd", "rd"]; 170 | const v = num % 100; 171 | return num + (suffixes[(v - 20) % 10] || suffixes[v] || suffixes[0]); 172 | } 173 | //Convert Markdown to HTML (Basic) 174 | function markdownToHTML(markdown) { 175 | return markdown 176 | .replace(/\*\*(.*?)\*\*/g, "$1") // Bold 177 | .replace(/\*(.*?)\*/g, "$1") // Italics 178 | .replace(/__(.*?)__/g, "$1") // Bold (alternative) 179 | .replace(/_(.*?)_/g, "$1") // Italics (alternative) 180 | .replace(/`(.*?)`/g, "$1"); // Inline code 181 | } 182 | 183 | module.exports = { 184 | getInitials , 185 | getRandomString , 186 | toKebaCase, 187 | toSnakeCase, 188 | toPascalCase, 189 | truncateString, 190 | removeWhitespace, 191 | toTitleCase, 192 | toSlug, 193 | maskString, 194 | handleURL, 195 | sanitizeHTML, 196 | getDomain, 197 | isValidEmail, 198 | parseQueryString, 199 | toQueryString, 200 | stripHTML, 201 | isValidURL, 202 | normalizeURL, 203 | obfuscateEmail, 204 | getRandomHexColor, 205 | getMetaTagContent, 206 | rgbToHex, 207 | hexToRgb, 208 | isJSON, 209 | addOrdinalSuffix, 210 | markdownToHTML 211 | } 212 | --------------------------------------------------------------------------------