π§ Exploring String Methos
Strings in JavaScript are primitive and immutable, which means their original value cannot be changed after creation. Instead of modifying the existing string, all string methods return a new string with the desired changes while leaving the original string unchanged.
π Extracting String Characters
There are 2 commonly used methods:
The
charAt(position)MethodUsing property access [ ] like in arrays
β String charAt( )
The charAt() method returns the character at a specified index in a string.
let text = "HELLO";
let char = text.charAt(0); // Hβ‘οΈ Property Access [ ]
Works like array indexing:
str[0]Read-only, returns
undefinedif not found
let text = "HELLO";
let char = text[0]; // Hπ Extracting String Parts
β¦οΈ String slice( )
slice(start, end)returns part of the stringSupports negative indexes
End index is not included
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13); // Bananaπ Changing Case
ποΈ String toUpperCase( )
Converts string to uppercase.
let text = "Hello";
let result = text.toUpperCase(); // HELLOποΈ String toLowerCase( )
Converts string to lowercase.
let text = "Hello";
let result = text.toLowerCase(); // helloπ String Concatenation
π° Using + or concat( )
You can join strings using either:
let text1 = "Hello";
let text2 = "World";
let text3 = text1 + " " + text2; // Hello Worldlet text3 = text1.concat(" ", text2); // Hello Worldπ Trimming Whitespace
βοΈ String trim( )
Removes whitespace from both ends of the string.
let text = " Hello World! ";
let result = text.trim(); // "Hello World!"π Replacing and Repeating
βΆοΈ String replace( )
Replaces the first occurrence of a match.
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "Codeveda"); // "Please visit Codeveda"π§© String replaceAll( )
Replaces all occurrences in a string.
let text = "I love cats. Cats are great.";
let newText = text.replaceAll("Cats", "Dogs"); // I love Dogs. Dogs are great"π String repeat( )
Repeats a string multiple times.
let text = "Hi! ";
let result = text.repeat(3); // Hi! Hi! Hi!π Searching Strings
π String includes( )
Checks if a string contains the given text.
let text = "Hello world";
text.includes("world"); // trueπͺ String startsWith( ) & endsWith( )
startsWith()β checks if a string starts with specified textendsWith()β checks if it ends with specified text
let text = "Hello world";
text.startsWith("Hello"); // true
text.endsWith("world"); // true<div class="infographic-strplay">
<style>
.infographic-strplay {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--ok: #1a7f4e;
--ok-soft: #e3f5ec;
--display-font: 'Fraunces', Georgia, serif;
--body-font: 'Inter', -apple-system, sans-serif;
--mono-font: 'IBM Plex Mono', 'Courier New', monospace;
margin: 0 auto;
box-sizing: border-box;
font-family: var(--body-font);
color: var(--ink);
background: var(--paper);
}
.infographic-strplay[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--ok: #5cd6a0;
--ok-soft: #16342a;
}
.infographic-strplay * { box-sizing: border-box; }
.infographic-strplay .ig-inner { padding: 1.75rem clamp(1.25rem, 5vw, 3rem) 2rem; }
.infographic-strplay .ig-title {
font-family: var(--display-font); font-size: clamp(1.4rem, 4.5vw, 1.9rem);
font-weight: 600; text-align: center; margin: 0 0 1.25rem;
}
.infographic-strplay .tabs { display: flex; gap: 0.4rem; justify-content: center; flex-wrap: wrap; }
.infographic-strplay .tab {
font: inherit; font-size: 0.78rem; font-weight: 600; border: 1px solid var(--line);
background: var(--paper); color: var(--ink-soft); padding: 0.4rem 0.8rem;
border-radius: 999px; cursor: pointer;
}
.infographic-strplay .tab.is-active { background: var(--accent); color: #fff; border-color: var(--accent); }
.infographic-strplay .chips { display: flex; flex-wrap: wrap; gap: 0.5rem; justify-content: center; margin-top: 1rem; }
.infographic-strplay .chip {
font: inherit; font-size: 0.8rem; font-weight: 700; font-family: var(--mono-font);
border: 1px solid var(--line); background: var(--paper-alt); color: var(--ink);
padding: 0.4rem 0.8rem; border-radius: 6px; cursor: pointer;
}
.infographic-strplay .chip.is-active { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); }
.infographic-strplay .playground {
margin-top: 1.5rem; background: var(--paper-alt); border: 1px solid var(--line); padding: 1.25rem 1rem;
}
.infographic-strplay .inputs-row { display: flex; flex-wrap: wrap; gap: 0.7rem; justify-content: center; }
.infographic-strplay .field { position: relative; display: flex; flex-direction: column; align-items: center; }
.infographic-strplay .field-tag {
font-size: 0.62rem; font-family: var(--mono-font); color: var(--accent); margin-bottom: 0.3rem;
}
.infographic-strplay .field input {
height: 2.3rem; font-family: var(--mono-font); font-size: 0.85rem; text-align: center;
border: 1px solid var(--line); background: var(--paper); color: var(--ink); border-radius: 5px; outline: none;
padding: 0 0.5rem;
}
.infographic-strplay .field input:focus { border-color: var(--accent); }
.infographic-strplay .field.wide input { width: 13rem; }
.infographic-strplay .field.narrow input { width: 4.2rem; }
.infographic-strplay .cs-row { display: flex; align-items: center; justify-content: center; gap: 0.6rem; margin-top: 1rem; }
.infographic-strplay .cs-label { font-family: var(--mono-font); font-size: 0.75rem; color: var(--ink-soft); }
.infographic-strplay .cs-btn {
font: inherit; font-size: 0.75rem; font-weight: 700; font-family: var(--mono-font);
border: 1px solid var(--line); background: var(--paper); color: var(--ink-soft);
padding: 0.3rem 0.7rem; border-radius: 999px; cursor: pointer;
}
.infographic-strplay .cs-btn.is-active { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); }
.infographic-strplay .cs-btn:disabled { opacity: 0.4; cursor: default; }
.infographic-strplay .call-line {
font-family: var(--mono-font); font-size: 0.85rem; text-align: center; font-weight: 700;
padding: 0.55rem 0.8rem; border-radius: 6px; margin-top: 1.1rem;
background: var(--accent-soft); color: var(--accent); border: 1px solid var(--accent);
word-break: break-word;
}
.infographic-strplay .result-row { display: flex; justify-content: center; margin-top: 0.9rem; }
.infographic-strplay .result-box {
font-family: var(--mono-font); font-size: 0.95rem; font-weight: 700;
padding: 0.5rem 1.1rem; background: var(--ok-soft); color: var(--ok); border: 1px solid var(--ok);
border-radius: 6px; min-width: 6rem; text-align: center;
box-shadow: 0 3px 8px rgba(0,0,0,0.1);
}
.infographic-strplay .caption {
text-align: center; font-size: 0.82rem; color: var(--ink-soft); margin-top: 1rem; min-height: 1.2em;
}
@media (prefers-reduced-motion: reduce) {
.infographic-strplay *, .infographic-strplay *::before, .infographic-strplay *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="ig-inner">
<h2 class="ig-title">String Methods Playground</h2>
<div class="tabs" id="tabs"></div>
<div class="chips" id="chips"></div>
<div class="playground">
<div class="inputs-row" id="inputsRow"></div>
<div class="cs-row" id="csRow">
<span class="cs-label">case sensitive</span>
<button class="cs-btn" id="csYes">Yes</button>
<button class="cs-btn" id="csNo">No</button>
</div>
<div class="call-line" id="callLine"></div>
<div class="result-row"><div class="result-box" id="resultBox"></div></div>
</div>
<p class="caption" id="caption"></p>
</div>
</div>
<script>
(function () {
const wrapper = document.currentScript.closest('.infographic-strplay')
|| document.querySelector('.infographic-strplay');
const bodyAttr = document.body.getAttribute('data-darkmode');
let dark;
if (bodyAttr === 'true') {
dark = true;
} else if (bodyAttr === 'false') {
dark = false;
} else {
const match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) wrapper.setAttribute('data-theme', 'dark');
function fmt(v) {
if (v === undefined) return 'undefined';
if (typeof v === 'boolean') return String(v);
return `"${v}"`;
}
function escapeRegex(s) {
return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const CATEGORIES = {
'Access': [
{
id: 'charAt', label: 'charAt()',
inputs: [{ key: 'str', tag: 'string', wide: true, default: 'HELLO' }, { key: 'idx', tag: 'index', default: '0' }],
call: v => `"${v.str}".charAt(${v.idx})`,
compute: v => v.str.charAt(Number(v.idx)),
caption: 'returns the character at that index'
},
{
id: 'bracket', label: 'str[i]',
inputs: [{ key: 'str', tag: 'string', wide: true, default: 'HELLO' }, { key: 'idx', tag: 'index', default: '0' }],
call: v => `"${v.str}"[${v.idx}]`,
compute: v => v.str[Number(v.idx)],
caption: 'same idea, array-style β undefined if out of range'
}
],
'Extract': [
{
id: 'slice', label: 'slice()',
inputs: [
{ key: 'str', tag: 'string', wide: true, default: 'Apple, Banana, Kiwi' },
{ key: 'start', tag: 'start', default: '7' },
{ key: 'end', tag: 'end', default: '13' }
],
call: v => `"${v.str}".slice(${v.start}, ${v.end})`,
compute: v => v.str.slice(Number(v.start), Number(v.end)),
caption: 'end index is not included'
}
],
'Case': [
{
id: 'upper', label: 'toUpperCase()',
inputs: [{ key: 'str', tag: 'string', wide: true, default: 'Hello' }],
call: v => `"${v.str}".toUpperCase()`,
compute: v => v.str.toUpperCase(),
caption: 'every letter becomes uppercase'
},
{
id: 'lower', label: 'toLowerCase()',
inputs: [{ key: 'str', tag: 'string', wide: true, default: 'Hello' }],
call: v => `"${v.str}".toLowerCase()`,
compute: v => v.str.toLowerCase(),
caption: 'every letter becomes lowercase'
}
],
'Join': [
{
id: 'plus', label: 'a + b',
inputs: [{ key: 'a', tag: 'text1', default: 'Hello' }, { key: 'b', tag: 'text2', default: 'World' }],
call: v => `"${v.a}" + " " + "${v.b}"`,
compute: v => `${v.a} ${v.b}`,
caption: 'joins with the + operator'
},
{
id: 'concat', label: 'concat()',
inputs: [{ key: 'a', tag: 'text1', default: 'Hello' }, { key: 'b', tag: 'text2', default: 'World' }],
call: v => `"${v.a}".concat(" ", "${v.b}")`,
compute: v => v.a.concat(' ', v.b),
caption: 'same result, called as a method'
}
],
'Trim': [
{
id: 'trim', label: 'trim()',
inputs: [{ key: 'str', tag: 'string (has spaces)', wide: true, default: ' Hello World! ' }],
call: v => `"${v.str}".trim()`,
compute: v => v.str.trim(),
caption: 'removes whitespace from both ends'
}
],
'Replace & Repeat': [
{
id: 'replace', label: 'replace()',
usesCase: true,
inputs: [
{ key: 'str', tag: 'string', wide: true, default: 'Please visit Microsoft!' },
{ key: 'search', tag: 'find', default: 'Microsoft' },
{ key: 'rep', tag: 'replace with', default: 'Codeveda' }
],
call: (v, cs) => cs
? `"${v.str}".replace("${v.search}", "${v.rep}")`
: `"${v.str}".replace(/${v.search}/i, "${v.rep}")`,
compute: (v, cs) => cs
? v.str.replace(v.search, v.rep)
: v.str.replace(new RegExp(escapeRegex(v.search), 'i'), v.rep),
caption: 'replaces only the first match'
},
{
id: 'replaceAll', label: 'replaceAll()',
usesCase: true,
inputs: [
{ key: 'str', tag: 'string', wide: true, default: 'I love cats. Cats are great.' },
{ key: 'search', tag: 'find', default: 'Cats' },
{ key: 'rep', tag: 'replace with', default: 'Dogs' }
],
call: (v, cs) => cs
? `"${v.str}".replaceAll("${v.search}", "${v.rep}")`
: `"${v.str}".replace(/${v.search}/gi, "${v.rep}")`,
compute: (v, cs) => cs
? v.str.replaceAll(v.search, v.rep)
: v.str.replace(new RegExp(escapeRegex(v.search), 'gi'), v.rep),
caption: 'replaces every match'
},
{
id: 'repeat', label: 'repeat()',
inputs: [{ key: 'str', tag: 'string', default: 'Hi! ' }, { key: 'count', tag: 'count', default: '3' }],
call: v => `"${v.str}".repeat(${v.count})`,
compute: v => v.str.repeat(Math.max(0, Number(v.count) || 0)),
caption: 'repeats the whole string n times'
}
],
'Search': [
{
id: 'includes', label: 'includes()',
usesCase: true,
inputs: [{ key: 'str', tag: 'string', wide: true, default: 'Hello world' }, { key: 'search', tag: 'find', default: 'world' }],
call: (v, cs) => cs
? `"${v.str}".includes("${v.search}")`
: `/${v.search}/i.test("${v.str}")`,
compute: (v, cs) => cs ? v.str.includes(v.search) : v.str.toLowerCase().includes(v.search.toLowerCase()),
caption: 'true if the text appears anywhere'
},
{
id: 'startsWith', label: 'startsWith()',
usesCase: true,
inputs: [{ key: 'str', tag: 'string', wide: true, default: 'Hello world' }, { key: 'search', tag: 'find', default: 'Hello' }],
call: (v, cs) => cs
? `"${v.str}".startsWith("${v.search}")`
: `/^${v.search}/i.test("${v.str}")`,
compute: (v, cs) => cs ? v.str.startsWith(v.search) : v.str.toLowerCase().startsWith(v.search.toLowerCase()),
caption: 'true if the string begins with it'
},
{
id: 'endsWith', label: 'endsWith()',
usesCase: true,
inputs: [{ key: 'str', tag: 'string', wide: true, default: 'Hello world' }, { key: 'search', tag: 'find', default: 'world' }],
call: (v, cs) => cs
? `"${v.str}".endsWith("${v.search}")`
: `/${v.search}$/i.test("${v.str}")`,
compute: (v, cs) => cs ? v.str.endsWith(v.search) : v.str.toLowerCase().endsWith(v.search.toLowerCase()),
caption: 'true if the string ends with it'
}
]
};
const tabsEl = wrapper.querySelector('#tabs');
const chipsEl = wrapper.querySelector('#chips');
const inputsRow = wrapper.querySelector('#inputsRow');
const callLine = wrapper.querySelector('#callLine');
const resultBox = wrapper.querySelector('#resultBox');
const caption = wrapper.querySelector('#caption');
const csYes = wrapper.querySelector('#csYes');
const csNo = wrapper.querySelector('#csNo');
const csRow = wrapper.querySelector('#csRow');
let currentCategory = 'Access';
let currentMethod = CATEGORIES.Access[0];
let values = {};
let caseSensitive = true;
function update() {
let result;
try { result = currentMethod.compute(values, caseSensitive); } catch (e) { result = 'Error'; }
callLine.textContent = currentMethod.call(values, caseSensitive);
resultBox.textContent = fmt(result);
caption.textContent = currentMethod.caption;
const applicable = !!currentMethod.usesCase;
csRow.style.display = applicable ? 'flex' : 'none';
csYes.classList.toggle('is-active', applicable && caseSensitive);
csNo.classList.toggle('is-active', applicable && !caseSensitive);
}
function buildInputs() {
inputsRow.innerHTML = '';
values = {};
currentMethod.inputs.forEach(spec => {
values[spec.key] = spec.default;
const field = document.createElement('div');
field.className = 'field' + (spec.wide ? ' wide' : ' narrow');
const tag = document.createElement('span');
tag.className = 'field-tag';
tag.textContent = spec.tag;
const input = document.createElement('input');
input.type = 'text';
input.value = spec.default;
input.addEventListener('input', () => { values[spec.key] = input.value; update(); });
field.appendChild(tag);
field.appendChild(input);
inputsRow.appendChild(field);
});
}
function selectMethod(method) {
currentMethod = method;
caseSensitive = true;
wrapper.querySelectorAll('.chip').forEach(c => c.classList.toggle('is-active', c.dataset.id === method.id));
buildInputs();
update();
}
csYes.addEventListener('click', () => { caseSensitive = true; update(); });
csNo.addEventListener('click', () => { caseSensitive = false; update(); });
function buildChips() {
chipsEl.innerHTML = '';
CATEGORIES[currentCategory].forEach((m, idx) => {
const chip = document.createElement('button');
chip.className = 'chip';
chip.textContent = m.label;
chip.dataset.id = m.id;
chip.addEventListener('click', () => selectMethod(m));
chipsEl.appendChild(chip);
if (idx === 0) selectMethod(m);
});
}
function selectCategory(name) {
currentCategory = name;
wrapper.querySelectorAll('.tab').forEach(t => t.classList.toggle('is-active', t.dataset.cat === name));
buildChips();
}
Object.keys(CATEGORIES).forEach(name => {
const tab = document.createElement('button');
tab.className = 'tab';
tab.textContent = name;
tab.dataset.cat = name;
tab.addEventListener('click', () => selectCategory(name));
tabsEl.appendChild(tab);
});
selectCategory('Access');
})();
</script>.demo {
font-family: system-ui, sans-serif;
padding: 16px;
}
.demo h1 {
color: #2563eb;
margin: 0 0 8px;
}
.demo p {
color: #4b5563;
margin: 0;
}document.querySelector('.demo h1')?.addEventListener('click', () => {
alert('Hello from live preview!');
});