agyanadda@gmail.com

JS String Methods

Strings and Numbers 1 min read Updated Dec 1, 2026 Topic 9 of 38

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>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method removes spaces from both ends of a string?

Exercise 2 Fill in the Blank

'a,b,c'.___(',') returns an array of three items.

Exercise 3 True / False

toUpperCase() changes the original string.

Frequently Asked Questions

They are similar, but slice accepts negative numbers (counting from the end): 'hello'.slice(-3) gives 'llo'.