VIDEO
Strings in JavaScript are immutable sequences of characters. JavaScript provides a rich set of built-in methods to work with strings — extracting, transforming, searching, and manipulating text.
A Quick Look at the Examples
console.log(String.fromCharCode(65, 66, 67)); // "ABC"
const str = "Hello";
console.log(str.charAt(0)); // "H"
console.log(str.charCodeAt(0)); // 72
const strObj = new String("Hello");
console.log(strObj.toString()); // "Hello"
console.log(strObj.valueOf()); // "Hello"
console.log(str.toUpperCase()); // "HELLO"
console.log("WORLD".toLowerCase()); // "world"
console.log("Hello".concat(", ", "World")); // "Hello, World"
console.log("Hello" + ", World!"); // "Hello, World!"
const str4 = "Hello, World!";
console.log(str4.slice(7, 12)); // "World"
console.log(str4.substring(0, 5)); // "Hello"
console.log(str4.substr(7, 5)); // "World"
console.log(str4.indexOf("World")); // 7
const str5 = "Hello, World! Hello again!";
console.log(str5.lastIndexOf("Hello")); // 14
console.log("JavaScript".includes("Script")); // true
console.log(str5.replace("World", "Universe")); // "Hello, Universe! Hello again!"
const str7 = "Apple,Banana,Cherry";
console.log(str7.split(",")); // ["Apple", "Banana", "Cherry"]
const str8 = " Hello, World! ";
console.log(str8.trim()); // "Hello, World!"
console.log(" Hello".trimStart()); // "Hello"
console.log("Hello ".trimEnd()); // "Hello"
const str11 = "5";
console.log(str11.padStart(3, "0")); // "005"
console.log(str11.padEnd(3, "0")); // "500"
console.log("Hello, World!".match(/o/g)); // ["o", "o"]
console.log("Hello, World!".search(/World/)); // 7
console.log("Hello".repeat(3)); // "HelloHelloHello"
a. String Properties — Part 1
Character & Code Methods
Method Description Example Result String.fromCharCode(...)Returns string from char codes String.fromCharCode(65, 66, 67)"ABC"charAt(index)Character at index "Hello".charAt(0)"H"charCodeAt(index)Unicode of character at index "Hello".charCodeAt(0)72
console.log(String.fromCharCode(65, 66, 67)); // "ABC"
console.log(String.fromCharCode(72, 101, 108, 108, 111)); // "Hello"
const str = "Hello";
console.log(str.charAt(0)); // "H"
console.log(str.charAt(4)); // "o"
console.log(str.charAt(99)); // "" (out of bounds)
console.log(str.charCodeAt(0)); // 72 (Unicode for 'H')
console.log(str.charCodeAt(1)); // 101 (Unicode for 'e')
Object Wrapper Methods
Method Description Example Result toString()Converts String object to primitive strObj.toString()"Hello"valueOf()Returns primitive value strObj.valueOf()"Hello"
const strObj = new String("Hello");
console.log(typeof strObj); // "object" ⚠️
console.log(strObj.toString()); // "Hello"
console.log(strObj.valueOf()); // "Hello"
// Note: Wrapper objects are rarely needed
// Use string literals instead: const str = "Hello";
⚠️ Warning: new String("Hello") creates an object , not a primitive. Use "Hello" (literal) instead.
Case Conversion
Method Description Example Result toUpperCase()Converts to uppercase "Hello".toUpperCase()"HELLO"toLowerCase()Converts to lowercase "WORLD".toLowerCase()"world"
const str = "Hello";
console.log(str.toUpperCase()); // "HELLO"
const str3 = "WORLD";
console.log(str3.toLowerCase()); // "world"
// Original string is unchanged (strings are immutable)
console.log(str); // "Hello"
Concatenation
Method Description Example Result concat(...values)Joins strings "Hello".concat(", ", "World")"Hello, World"+ operatorConcatenates strings "Hello" + ", World!""Hello, World!"
const str1 = "Hello";
const str2 = "World";
// Method
console.log(str1.concat(", ", str2)); // "Hello, World"
// Operator (preferred)
console.log(str1 + ", " + str2); // "Hello, World"
// Template literal (modern)
console.log(`${str1}, ${str2}`); // "Hello, World"
b. String Properties — Part 2
Extraction Methods
Method Description Example Result slice(start, end)Extracts section (supports negative) "Hello, World!".slice(7, 12)"World"substring(start, end)Similar to slice (no negatives) "Hello, World!".substring(0, 5)"Hello"substr(start, length)Extracts length chars (deprecated) "Hello, World!".substr(7, 5)"World"
const str = "Hello, World!";
// slice — supports negative indices
console.log(str.slice(7, 12)); // "World"
console.log(str.slice(-6, -1)); // "World"
console.log(str.slice(7)); // "World!"
// substring — negative treated as 0
console.log(str.substring(0, 5)); // "Hello"
console.log(str.substring(7)); // "World!"
// substr — deprecated, avoid
console.log(str.substr(7, 5)); // "World"
slice vs substring vs substr:
Input slice(1, 4)substring(1, 4)substr(1, 4)"Hello""ell""ell""ello"slice(-3)"llo""Hello" (negative → 0)"llo" (from end)
Search Methods
Method Description Example Result indexOf(value, from)First occurrence "Hello, World!".indexOf("World")7lastIndexOf(value, from)Last occurrence "Hello Hello".lastIndexOf("Hello")6includes(value, start)Contains substring "JavaScript".includes("Script")true
const str = "Hello, World! Hello again!";
// indexOf — first occurrence
console.log(str.indexOf("Hello")); // 0
console.log(str.indexOf("Hello", 1)); // 14 (search from index 1)
console.log(str.indexOf("xyz")); // -1 (not found)
// lastIndexOf — last occurrence
console.log(str.lastIndexOf("Hello")); // 14
// includes — boolean check
console.log("JavaScript".includes("Script")); // true
console.log("JavaScript".includes("Python")); // false
console.log("JavaScript".includes("Java", 0)); // true
Replace and Split
Method Description Example Result replace(search, newValue)Replaces first match "Hello World".replace("World", "Universe")"Hello Universe"replaceAll(search, newValue)Replaces all matches (ES2021) "Hello Hello".replaceAll("Hello", "Hi")"Hi Hi"split(separator, limit)Splits into array "Apple,Banana".split(",")["Apple", "Banana"]
// replace — only first match by default
const str = "Hello, World! Hello again!";
console.log(str.replace("Hello", "Hi")); // "Hi, World! Hello again!"
// replaceAll — all matches (ES2021)
console.log(str.replaceAll("Hello", "Hi")); // "Hi, World! Hi again!"
// replace with regex for all matches
console.log(str.replace(/Hello/g, "Hi")); // "Hi, World! Hi again!"
// split
const csv = "Apple,Banana,Cherry";
console.log(csv.split(",")); // ["Apple", "Banana", "Cherry"]
console.log(csv.split(",", 2)); // ["Apple", "Banana"]
console.log("Hello".split("")); // ["H", "e", "l", "l", "o"]
c. String Properties — Part 3
Trimming Whitespace
Method Description Example Result trim()Removes whitespace from both ends " Hello ".trim()"Hello"trimStart()Removes leading whitespace (ES2019) " Hello".trimStart()"Hello"trimEnd()Removes trailing whitespace (ES2019) "Hello ".trimEnd()"Hello"
const str = " Hello, World! ";
console.log(str.trim()); // "Hello, World!"
console.log(str.trimStart()); // "Hello, World! "
console.log(str.trimEnd()); // " Hello, World!"
// Original string is unchanged
console.log(str); // " Hello, World! "
Padding
Method Description Example Result padStart(len, str)Pads at start "5".padStart(3, "0")"005"padEnd(len, str)Pads at end "5".padEnd(3, "0")"500"
const str = "5";
console.log(str.padStart(3, "0")); // "005"
console.log(str.padEnd(3, "0")); // "500"
console.log("42".padStart(6, "0")); // "000042"
console.log("abc".padEnd(6, "*")); // "abc***"
console.log("abc".padStart(6)); // " abc" (space default)
// Practical: format times
const h = "9".padStart(2, "0"); // "09"
const m = "5".padStart(2, "0"); // "05"
console.log(`${h}:${m}`); // "09:05"
Regex Methods
Method Description Example Result match(regexp)Returns matches array "Hello".match(/l/g)["l", "l"]search(regexp)Index of first match "Hello World".search(/World/)6
const str = "Hello, World!";
// match — returns array of matches
console.log(str.match(/o/g)); // ["o", "o"]
console.log(str.match(/xyz/)); // null
console.log(str.match(/l+/g)); // ["ll"]
// search — returns index of first match
console.log(str.search(/World/)); // 7
console.log(str.search(/xyz/)); // -1
Repeat
Method Description Example Result repeat(count)Repeats string n times "Hello".repeat(3)"HelloHelloHello"
console.log("Hello".repeat(3)); // "HelloHelloHello"
console.log("=".repeat(20)); // "===================="
console.log("ab".repeat(0)); // ""
Practical: Build a divider:
console.log("=".repeat(40));
console.log("My Title".padStart(20).padEnd(40, "="));
console.log("=".repeat(40));
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Methods</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
color: #333;
line-height: 1.6;
}
h1 { color: #007bff; border-bottom: 3px solid #007bff; padding-bottom: 10px; }
h2 { color: #28a745; border-left: 4px solid #28a745; padding-left: 15px; margin-top: 30px; }
.demo-box {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin: 15px 0;
}
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.8;
}
.keyword { color: #569cd6; }
.string { color: #ce9178; }
.number { color: #b5cea8; }
.function { color: #dcdcaa; }
.comment { color: #6a9955; }
.boolean { color: #569cd6; }
#output {
background: #e9ecef;
padding: 15px;
border-radius: 8px;
margin-top: 15px;
min-height: 40px;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
border-left: 4px solid #007bff;
white-space: pre-wrap;
}
table {
width: 100%;
border-collapse: collapse;
margin: 15px 0;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
}
th { background: #007bff; color: white; }
tr:nth-child(even) { background: #f8f9fa; }
.btn {
padding: 10px 20px;
background: #007bff;
color: white;
border: none;
border-radius: 6px;
font-size: 1em;
font-weight: bold;
cursor: pointer;
margin: 5px;
transition: all 0.3s;
}
.btn:hover {
background: #0056b3;
transform: translateY(-2px);
}
.btn-success { background: #28a745; }
.btn-success:hover { background: #1e7e34; }
.input-group {
margin: 10px 0;
}
.input-group label {
display: inline-block;
min-width: 150px;
font-weight: bold;
}
.input-group input {
padding: 8px 12px;
border: 2px solid #ddd;
border-radius: 6px;
font-size: 1em;
width: 300px;
}
.input-group input:focus {
outline: none;
border-color: #007bff;
}
.string-display {
font-family: 'Courier New', monospace;
font-size: 1.2em;
color: #007bff;
background: #f8f9fa;
padding: 15px;
border-radius: 8px;
margin: 10px 0;
border-left: 4px solid #007bff;
word-break: break-all;
}
</style>
</head>
<body>
<h1>String Methods</h1>
<div class="demo-box">
<h2>1. Character & Code Methods</h2>
<pre>
console.log(<span class="function">String.fromCharCode</span>(<span class="number">65</span>, <span class="number">66</span>, <span class="number">67</span>)); <span class="comment">// "ABC"</span>
<span class="keyword">const</span> str = <span class="string">"Hello"</span>;
console.log(str.<span class="function">charAt</span>(<span class="number">0</span>)); <span class="comment">// "H"</span>
console.log(str.<span class="function">charCodeAt</span>(<span class="number">0</span>)); <span class="comment">// 72</span>
</pre>
</div>
<div class="demo-box">
<h2>2. Case Conversion & Concatenation</h2>
<pre>
console.log(<span class="string">"Hello"</span>.<span class="function">toUpperCase</span>()); <span class="comment">// "HELLO"</span>
console.log(<span class="string">"WORLD"</span>.<span class="function">toLowerCase</span>()); <span class="comment">// "world"</span>
console.log(<span class="string">"Hello"</span>.<span class="function">concat</span>(<span class="string">", "</span>, <span class="string">"World"</span>)); <span class="comment">// "Hello, World"</span>
</pre>
</div>
<div class="demo-box">
<h2>3. Extraction Methods</h2>
<pre>
<span class="keyword">const</span> str = <span class="string">"Hello, World!"</span>;
console.log(str.<span class="function">slice</span>(<span class="number">7</span>, <span class="number">12</span>)); <span class="comment">// "World"</span>
console.log(str.<span class="function">substring</span>(<span class="number">0</span>, <span class="number">5</span>)); <span class="comment">// "Hello"</span>
console.log(str.<span class="function">substr</span>(<span class="number">7</span>, <span class="number">5</span>)); <span class="comment">// "World" (deprecated)</span>
</pre>
</div>
<div class="demo-box">
<h2>4. Search Methods</h2>
<pre>
<span class="keyword">const</span> str = <span class="string">"Hello, World! Hello again!"</span>;
console.log(str.<span class="function">indexOf</span>(<span class="string">"Hello"</span>)); <span class="comment">// 0</span>
console.log(str.<span class="function">lastIndexOf</span>(<span class="string">"Hello"</span>)); <span class="comment">// 14</span>
console.log(str.<span class="function">includes</span>(<span class="string">"World"</span>)); <span class="comment">// true</span>
</pre>
</div>
<div class="demo-box">
<h2>5. Replace & Split</h2>
<pre>
console.log(<span class="string">"Hello, World!"</span>.<span class="function">replace</span>(<span class="string">"World"</span>, <span class="string">"Universe"</span>));
<span class="comment">// "Hello, Universe!"</span>
console.log(<span class="string">"Apple,Banana,Cherry"</span>.<span class="function">split</span>(<span class="string">","</span>));
<span class="comment">// ["Apple", "Banana", "Cherry"]</span>
</pre>
</div>
<div class="demo-box">
<h2>6. Trim & Pad</h2>
<pre>
console.log(<span class="string">" Hello "</span>.<span class="function">trim</span>()); <span class="comment">// "Hello"</span>
console.log(<span class="string">" Hello"</span>.<span class="function">trimStart</span>()); <span class="comment">// "Hello"</span>
console.log(<span class="string">"Hello "</span>.<span class="function">trimEnd</span>()); <span class="comment">// "Hello"</span>
console.log(<span class="string">"5"</span>.<span class="function">padStart</span>(<span class="number">3</span>, <span class="string">"0"</span>)); <span class="comment">// "005"</span>
console.log(<span class="string">"5"</span>.<span class="function">padEnd</span>(<span class="number">3</span>, <span class="string">"0"</span>)); <span class="comment">// "500"</span>
</pre>
</div>
<div class="demo-box">
<h2>7. Interactive: String Playground</h2>
<div class="input-group">
<label for="stringInput">Enter text:</label>
<input type="text" id="stringInput" value="Hello, World!">
</div>
<div style="margin: 10px 0;">
<button class="btn" onclick="applyMethod('upper')">UPPERCASE</button>
<button class="btn" onclick="applyMethod('lower')">lowercase</button>
<button class="btn" onclick="applyMethod('reverse')">Reverse</button>
<button class="btn" onclick="applyMethod('length')">Length</button>
<button class="btn btn-success" onclick="applyMethod('trim')">Trim</button>
<button class="btn" onclick="applyMethod('split')">Split</button>
<button class="btn" onclick="applyMethod('reset')">Reset</button>
</div>
<div class="string-display" id="stringDisplay">Hello, World!</div>
<div id="methodOutput"></div>
</div>
<div class="demo-box">
<h2>8. String Methods Cheat Sheet</h2>
<table>
<tr>
<th>Category</th>
<th>Methods</th>
</tr>
<tr>
<td><strong>Character</strong></td>
<td><code>charAt()</code>, <code>charCodeAt()</code>, <code>fromCharCode()</code></td>
</tr>
<tr>
<td><strong>Case</strong></td>
<td><code>toUpperCase()</code>, <code>toLowerCase()</code></td>
</tr>
<tr>
<td><strong>Concatenation</strong></td>
<td><code>concat()</code>, <code>+</code>, template literals</td>
</tr>
<tr>
<td><strong>Extraction</strong></td>
<td><code>slice()</code>, <code>substring()</code>, <code>substr()</code></td>
</tr>
<tr>
<td><strong>Search</strong></td>
<td><code>indexOf()</code>, <code>lastIndexOf()</code>, <code>includes()</code>, <code>search()</code></td>
</tr>
<tr>
<td><strong>Replace</strong></td>
<td><code>replace()</code>, <code>replaceAll()</code></td>
</tr>
<tr>
<td><strong>Split</strong></td>
<td><code>split()</code></td>
</tr>
<tr>
<td><strong>Trim</strong></td>
<td><code>trim()</code>, <code>trimStart()</code>, <code>trimEnd()</code></td>
</tr>
<tr>
<td><strong>Pad</strong></td>
<td><code>padStart()</code>, <code>padEnd()</code></td>
</tr>
<tr>
<td><strong>Regex</strong></td>
<td><code>match()</code>, <code>search()</code>, <code>replace()</code></td>
</tr>
<tr>
<td><strong>Repeat</strong></td>
<td><code>repeat()</code></td>
</tr>
</table>
</div>
<div class="demo-box">
<h2>9. Live Output — All Examples</h2>
<div id="output">Loading...</div>
</div>
<script>
// ============================================
// String Methods — Live Demo
// ============================================
let results = [];
// 1. Character & code methods
results.push('📌 Character & Code Methods:\n');
results.push(' String.fromCharCode(65, 66, 67) → "' + String.fromCharCode(65, 66, 67) + '"');
results.push(' "Hello".charAt(0) → "' + "Hello".charAt(0) + '"');
results.push(' "Hello".charCodeAt(0) → ' + "Hello".charCodeAt(0));
results.push('');
// 2. Case conversion
results.push('📌 Case Conversion:\n');
results.push(' "Hello".toUpperCase() → "' + "Hello".toUpperCase() + '"');
results.push(' "WORLD".toLowerCase() → "' + "WORLD".toLowerCase() + '"');
results.push('');
// 3. Concatenation
results.push('📌 Concatenation:\n');
results.push(' "Hello".concat(", ", "World") → "' + "Hello".concat(", ", "World") + '"');
results.push(' "Hello" + ", World!" → "' + ("Hello" + ", World!") + '"');
results.push('');
// 4. Extraction
results.push('📌 Extraction:\n');
const str = "Hello, World!";
results.push(' "Hello, World!".slice(7, 12) → "' + str.slice(7, 12) + '"');
results.push(' "Hello, World!".substring(0, 5) → "' + str.substring(0, 5) + '"');
results.push(' "Hello, World!".substr(7, 5) → "' + str.substr(7, 5) + '" (deprecated)');
results.push('');
// 5. Search
results.push('📌 Search:\n');
const str5 = "Hello, World! Hello again!";
results.push(' "Hello, World!".indexOf("World") → ' + str.indexOf("World"));
results.push(' "Hello, World! Hello again!".lastIndexOf("Hello") → ' + str5.lastIndexOf("Hello"));
results.push(' "JavaScript".includes("Script") → ' + "JavaScript".includes("Script"));
results.push('');
// 6. Replace & split
results.push('📌 Replace & Split:\n');
results.push(' "Hello, World!".replace("World", "Universe") → "' + "Hello, World!".replace("World", "Universe") + '"');
results.push(' "Apple,Banana,Cherry".split(",") → [' + "Apple,Banana,Cherry".split(",").map(s => '"' + s + '"').join(', ') + ']');
results.push('');
// 7. Trim
results.push('📌 Trim:\n');
results.push(' " Hello, World! ".trim() → "' + " Hello, World! ".trim() + '"');
results.push(' " Hello".trimStart() → "' + " Hello".trimStart() + '"');
results.push(' "Hello ".trimEnd() → "' + "Hello ".trimEnd() + '"');
results.push('');
// 8. Pad
results.push('📌 Pad:\n');
results.push(' "5".padStart(3, "0") → "' + "5".padStart(3, "0") + '"');
results.push(' "5".padEnd(3, "0") → "' + "5".padEnd(3, "0") + '"');
results.push('');
// 9. Regex
results.push('📌 Regex Methods:\n');
results.push(' "Hello, World!".match(/o/g) → [' + "Hello, World!".match(/o/g).map(s => '"' + s + '"').join(', ') + ']');
results.push(' "Hello, World!".search(/World/) → ' + "Hello, World!".search(/World/));
results.push('');
// 10. Repeat
results.push('📌 Repeat:\n');
results.push(' "Hello".repeat(3) → "' + "Hello".repeat(3) + '"');
results.push(' "=".repeat(20) → "' + "=".repeat(20) + '"');
results.push('');
// 11. Practical: title case
results.push('📌 Practical: Title Case:\n');
function titleCase(str) {
return str.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
}
results.push(' titleCase("hello world") → "' + titleCase("hello world") + '"');
results.push('');
// 12. Practical: truncate
results.push('📌 Practical: Truncate:\n');
function truncate(str, maxLength) {
if (str.length <= maxLength) return str;
return str.slice(0, maxLength) + '...';
}
results.push(' truncate("Hello, World!", 8) → "' + truncate("Hello, World!", 8) + '"');
results.push('');
// 13. Practical: slug
results.push('📌 Practical: Slug:\n');
function slugify(str) {
return str.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}
results.push(' slugify("Hello, World!") → "' + slugify("Hello, World!") + '"');
results.push(' slugify(" My Blog Post ") → "' + slugify(" My Blog Post ") + '"');
results.push('');
// 14. Practical: format time
results.push('📌 Practical: Format Time:\n');
const h = "9".padStart(2, "0");
const m = "5".padStart(2, "0");
results.push(' "9".padStart(2, "0") + ":" + "5".padStart(2, "0") → "' + h + ':' + m + '"');
document.getElementById('output').textContent = results.join('\n');
// ============================================
// Interactive String Playground
// ============================================
let originalString = "Hello, World!";
function applyMethod(method) {
const input = document.getElementById('stringInput').value;
const display = document.getElementById('stringDisplay');
const output = document.getElementById('methodOutput');
switch (method) {
case 'upper':
display.textContent = input.toUpperCase();
output.innerHTML = `<p><code>"${input}".toUpperCase()</code></p>`;
break;
case 'lower':
display.textContent = input.toLowerCase();
output.innerHTML = `<p><code>"${input}".toLowerCase()</code></p>`;
break;
case 'reverse':
const reversed = input.split('').reverse().join('');
display.textContent = reversed;
output.innerHTML = `<p><code>"${input}".split('').reverse().join('')</code></p>`;
break;
case 'length':
display.textContent = input.length + ' characters';
output.innerHTML = `<p><code>"${input}".length</code></p>`;
break;
case 'trim':
const trimmed = input.trim();
display.textContent = `"${trimmed}"`;
output.innerHTML = `<p><code>"${input}".trim()</code> → removed ${input.length - trimmed.length} whitespace chars</p>`;
break;
case 'split':
const parts = input.split(' ');
display.textContent = JSON.stringify(parts);
output.innerHTML = `<p><code>"${input}".split(' ')</code></p>`;
break;
case 'reset':
display.textContent = originalString;
document.getElementById('stringInput').value = originalString;
output.innerHTML = '';
break;
}
}
</script>
</body>
</html>
Quick Reference
Character & Code
Method Description Example fromCharCode()Char from code String.fromCharCode(65) → "A"charAt(i)Char at index "Hi".charAt(0) → "H"charCodeAt(i)Unicode at index "Hi".charCodeAt(0) → 72
Case & Concatenation
Method Description Example toUpperCase()To uppercase "hi".toUpperCase() → "HI"toLowerCase()To lowercase "HI".toLowerCase() → "hi"concat()Join strings "a".concat("b") → "ab"
Extraction
Method Description Example slice(s, e)Extract (negative OK) "Hello".slice(1, 3) → "el"substring(s, e)Extract (no negative) "Hello".substring(1, 3) → "el"substr(s, l)Extract length (deprecated) "Hello".substr(1, 3) → "ell"
Search
Method Description Example indexOf()First index "Hello".indexOf("l") → 2lastIndexOf()Last index "Hello".lastIndexOf("l") → 3includes()Contains? "Hello".includes("ell") → true
Transform
Method Description Example replace()Replace first "aaa".replace("a", "b") → "baa"replaceAll()Replace all "aaa".replaceAll("a", "b") → "bbb"split()Split to array "a,b".split(",") → ["a", "b"]trim()Remove whitespace " a ".trim() → "a"padStart()Pad at start "5".padStart(3, "0") → "005"padEnd()Pad at end "5".padEnd(3, "0") → "500"repeat()Repeat n times "ab".repeat(2) → "abab"
Best Practices
✅ Do This:
// Use template literals for interpolation
const greeting = `Hello, ${name}!`;
// Use slice() for extraction (supports negatives)
const part = str.slice(1, 5);
const last = str.slice(-3);
// Use trim() for user input
const clean = input.trim();
// Use padStart() for formatting
const time = `${hours.padStart(2, '0')}:${minutes.padStart(2, '0')}`;
// Use includes() for existence checks
if (str.includes('search')) { }
// Chain methods
const result = str.trim().toLowerCase().replace(/\s+/g, '-');
❌ Don’t Do This:
// Don't use new String() (creates object)
const str = new String("Hello"); // ❌ Use "Hello"
// Don't use substr() (deprecated)
str.substr(0, 5); // ❌ Use slice() or substring()
// Don't assume replace() replaces all
"aaa".replace("a", "b"); // "baa" (only first!)
// Don't forget strings are immutable
let s = "hello";
s.toUpperCase(); // ❌ Doesn't change s
s = s.toUpperCase(); // ✅ Reassign
// Don't use string concatenation for many parts
let result = "a" + "b" + "c" + "d"; // Use template literal or array.join()
Common Pitfalls
Pitfall Problem Solution new String()Creates object Use literal "text" substr()Deprecated Use slice() or substring() replace() replaces firstNot all Use replaceAll() or /g regex Strings immutable Methods return new strings Reassign result slice(-1)From end Works — returns last char substring(-1)Treated as 0 Use slice() for negatives
Pro Tip: Strings in JavaScript are immutable — every method returns a new string , leaving the original unchanged. Use slice() for extraction (it supports negative indices), includes() for existence checks, trim() for cleaning user input, and padStart()/padEnd() for formatting. Chain methods for powerful transformations: str.trim().toLowerCase().replace(/\s+/g, '-'). And remember: replace() only replaces the first match — use replaceAll() or a regex with /g for all matches!
← Previous JavaScript 21 🧬 Mutability Next → JavaScript 23 🧬 rest parameters
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for: ✅ Finance (Mortgage, Interest, Inflation) ✅ Tech (Base64, JSON, Dev Suite, IP) ✅ Health (BMI, BMR, TDEE) ✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private 🔒 No data leaves your device 💎 100% Free
🔗 Use it now: https://tools.kandz.me 🔖 Bookmark it—you’ll need it later!