Strings have many built-in methods.
| Method | Example | Result |
|---|---|---|
toUpperCase() |
'hi'.toUpperCase() |
'HI' |
toLowerCase() |
'HI'.toLowerCase() |
'hi' |
trim() |
' hi '.trim() |
'hi' |
includes() |
'hello'.includes('ell') |
true |
indexOf() |
'hello'.indexOf('l') |
2 |
slice(start, end) |
'hello'.slice(1, 4) |
'ell' |
replace() |
'a-b'.replace('-', '+') |
'a+b' |
replaceAll() |
'a-b-c'.replaceAll('-', '') |
'abc' |
split() |
'a,b,c'.split(',') |
['a','b','c'] |
startsWith() |
'https://x'.startsWith('https') |
true |
padStart() |
'5'.padStart(3, '0') |
'005' |
All of these return a new value.
Example
Example — Cleaning user input
HTML
<pre id="out"></pre>
<script>
const input = ' Asha Kumari ';
const clean = input.trim();
const out = [
'Trimmed: "' + clean + '"',
'Upper: ' + clean.toUpperCase(),
'Has "Kumari": ' + clean.includes('Kumari'),
'First name: ' + clean.split(' ')[0],
'Username: ' + clean.toLowerCase().replaceAll(' ', '_'),
'Roll no: ' + '7'.padStart(4, '0')
];
document.getElementById('out').textContent = out.join('\n');
</script>