#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 39 of 50easy

What are common String methods in JavaScript?

Understanding string manipulation methods.

What You'll Learn

  • Searching strings
  • Transforming strings
  • Extracting substrings

Searching

code.jsJavaScript
const str = 'Hello World';

// includes
str.includes('World'); // true

// startsWith / endsWith
str.startsWith('Hello'); // true
str.endsWith('World');   // true

// indexOf / lastIndexOf
str.indexOf('o');      // 4
str.lastIndexOf('o');  // 7

// search (regex)
str.search(/world/i);  // 6

Transforming

code.jsJavaScript
// Case
'hello'.toUpperCase(); // 'HELLO'
'HELLO'.toLowerCase(); // 'hello'

// Trim
'  hello  '.trim();      // 'hello'
'  hello  '.trimStart(); // 'hello  '
'  hello  '.trimEnd();   // '  hello'

// Replace
'hello'.replace('l', 'L');      // 'heLlo'
'hello'.replaceAll('l', 'L');   // 'heLLo'
'hello'.replace(/l/g, 'L');     // 'heLLo'

// Pad
'5'.padStart(3, '0');  // '005'
'5'.padEnd(3, '0');    // '500'

// Repeat
'ab'.repeat(3);        // 'ababab'

Extracting

code.jsJavaScript
const str = 'Hello World';

// slice (start, end)
str.slice(0, 5);   // 'Hello'
str.slice(-5);     // 'World'

// substring (start, end)
str.substring(0, 5); // 'Hello'

// split
'a,b,c'.split(',');  // ['a', 'b', 'c']
'hello'.split('');   // ['h', 'e', 'l', 'l', 'o']

// charAt
str.charAt(0);       // 'H'
str[0];              // 'H'

Modern Methods

code.jsJavaScript
// at() - negative indexing
'hello'.at(-1);  // 'o'
'hello'.at(0);   // 'h'