JavaScript String

Why should you care about JavaScript String?

Strings are everywhere in real apps: form inputs, API data, search, validation, and UI labels. If you handle strings well, your code becomes much more practical and reliable.

A string is just text in JavaScript. It can contain letters, numbers, symbols, spaces, or a mix of everything. You write strings using single quotes ('), double quotes ("), or backticks (`).

JavaScript Strings - character indexes, quote types, and common methods

javascript

//Example
let singleQuoteString = 'Hello, World!';
let doubleQuoteString = "JavaScript is fun!";
let name = 'Alice';
let templateLiteralString = `Hello, ${name}! Welcome to JavaScript.`;
let numberString = '12345';
let multilineString = `This is a 
multiline string in JavaScript.`;

Single quotes and double quotes both work for strings. The key rule is simple: opening and closing quotes must match. If you start with single quotes, end with single quotes. Same idea for double quotes.

javascript

//Correct
let str1 = 'Hello, World!';
let str2 = "JavaScript is fun!";

//Incorrect
let str3 = "Hello, World!';
let str4 = "JavaScript is fun!';

If your text already contains a quote, you can either switch quote type or escape it with a backslash. For example:

javascript

let str3 = "It's a sunny day.";
let str4 = 'He said, "Hello!"';
let str5 = 'It\'s a sunny day.';
let str6 = "He said, \"Hello!\"";

Sometimes a string needs special characters like a new line, quote, or backslash. In those cases, use an escape sequence. A backslash (\) tells JavaScript to treat the next character specially.

  • \': Single quote
  • \": Double quote
  • \\: Backslash
  • \n: New line
  • \t:Tab
  • \r: Carriage return
  • \b: Backspace
  • \f: Form feed

javascript

let escapeExample = 'I\'m learning JavaScript.\nIt\'s fun!';
let text = "He said, \"JavaScript is awesome!\" \nAnd I couldn't agree more.";
console.log(text);

// Output:
// I'm learning JavaScript.
// It's fun!
// He said, "JavaScript is awesome!" 
// And I couldn't agree more.

A string literal is text written directly in your code, wrapped in quotes or backticks. It is the actual value itself.

javascript

let str = 'Hello World';
let funStr = "JavaScript is fun";

In day-to-day coding, you will usually use string literals instead of new String() objects because they are simpler and cleaner.

To count characters in a string, use the .length property. It counts letters, symbols, and spaces.

javascript

let text = 'Hello World';
console.log(text.length);  // Output: 11

console.log(text.length()); //wrong

Note: length is a property, not a function.

JavaScript lets you access string characters by index, similar to arrays. Index starts from 0.

javascript

const str = "hello";
console.log(str[0]); // Output: 'h'
console.log(str[4]); // Output: 'o'

You can also loop through a string character by character using for...of.

javascript

const str = "hello";
for (const char of str) {
    console.log(char);
}
// Output:
// h
// e
// l
// l
// o

Strings are immutable. That means you cannot change an individual character directly. If you need an updated value, create a new string.

javascript

let str = "hello";
// Attempting to change a character (this won't work)
str[0] = "H"; 
console.log(str); // Output: 'hello'

// To change it, create a new string
str = "H" + str.slice(1);
console.log(str); // Output: 'Hello'

JavaScript includes many built-in string methods for searching, slicing, replacing, trimming, and changing case. Expand any method below to see syntax and examples.

  • charAt(): character at index
  • concat(): join strings
  • endsWith(): check suffix
  • includes(): check substring
  • indexOf(): first occurrence
  • lastIndexOf(): last occurrence
  • match(): regex match
  • padEnd(): pad right
  • padStart(): pad left
  • repeat(): repeat string
  • replace(): find and replace
  • search(): regex search
  • slice(): extract substring
  • split(): split into array
  • startsWith(): check prefix
  • substring(): extract substring
  • toLowerCase(): to lower case
  • toUpperCase(): to upper case
  • trim(): remove whitespace
  • trimEnd(): remove trailing whitespace
  • trimStart(): remove leading whitespace
  • valueOf(): primitive value

Returns the character at a specified index in a string.

charAt(index)

 str = "Hello"
  +-------------------+
  | H | e | l | l | o |
  +-------------------+
    0   1   2   3   4

 "Hello".charAt(1)  ?  "e"
 "Hello".charAt(4)  ?  "o"

javascript

//Syntax: string.charAt(index)

//Example 
let text = 'Hello';
console.log(text.charAt(1));  // Output: 'e'

Joins two or more strings into one.

concat()

 str1 = "Hello"   str2 = " "   str3 = "World"
 +-------+        +---+        +-------+
 | Hello |   +    |   |   +    | World |
 +-------+        +---+        +-------+
                      |
                      ?
             +-------------+
             | Hello World |
             +-------------+

javascript

//Syntax: string.concat(string2, string3, ...)
                              
//Example 
let str1 = 'Hello';
let str2 = 'World';
console.log(str1.concat(' ', str2));  // Output: 'Hello World'

Checks if a string ends with a specified substring.

endsWith(searchString)

 str = "Hello World"
  H  e  l  l  o     W  o  r  l  d
 ?------------------------------?
                         +------+
                          "World"  ? match at end

 "Hello World".endsWith("World")  ?  true
 "Hello World".endsWith("Hello")  ?  false

javascript

//Syntax: string.endsWith(searchString)
                              
//Example 
let text = 'Hello World';
console.log(text.endsWith('World'));  // Output: true

Checks if a string contains a specified value.

includes(searchString)

 str = "Hello World"
  H  e  l  l  o     W  o  r  l  d
                    +------+
                    "World"  ? found

 "Hello World".includes("World")  ?  true
 "Hello World".includes("world")  ?  false  (case-sensitive)

javascript

//Syntax: string.includes(searchString)
                              
//Example 
let text = 'Hello World';
console.log(text.includes('World'));  // Output: true

Returns the index of the first occurrence of a specified value. If not found, it returns -1.

indexOf(searchValue)

 str = "Hello World"
  +-------------------------------------------+
  | H | e | l | l | o |   | W | o | r | l | d |
  +-------------------------------------------+
    0   1   2   3   4   5   6   7   8   9  10
                            +---------------+
                             "World" starts at index 6

 "Hello World".indexOf("World")  ?  6
 "Hello World".indexOf("xyz")    ?  -1

javascript

//Syntax: string.indexOf(searchValue)

//Example                                
let text = 'Hello World';
console.log(text.indexOf('World'));  // Output: 6

Returns the index of the last occurrence of a specified value. If not found, returns -1.

lastIndexOf(searchValue)

 str = "Hello World World"
  0    5    10   15
  H e l l o   W o r l d   W  o  r  l  d
              ?            ?
           index 6      index 12  ? last occurrence

 "Hello World World".lastIndexOf("World")  ?  12
 "Hello World World".indexOf("World")      ?   6  (first)

javascript

//Syntax: string.lastIndexOf(searchValue)
         
//Example                                
let text = 'Hello World World';
console.log(text.lastIndexOf('World'));  // Output: 12

Searches a string for a match against a regular expression and returns the matches.

match(regex)

 str = "The rain in Spain stays mainly in the plain"
        ---+  +---+           +-----+          +---+
              "ain"           "ain"             "ain"

 str.match(/ain/g)  ?  ["ain", "ain", "ain"]
                               ?
                    global flag finds all matches

javascript

//Syntax: string.match(regex)

//Example                              
let text = 'The rain in Spain stays mainly in the plain';
console.log(text.match(/ain/g));  // Output: ['ain', 'ain', 'ain']

Pads the current string from the end with another string until it reaches the desired length.

padEnd(targetLength, padString)

 str = "Hello"   targetLength = 8   padString = "!"

 Before:          After:
 +-------+        +-------------------+
 | Hello |  ?     | Hello | ! | ! | ! |
 +-------+        +-------------------+
  length=5         length=8  (padded at end)

javascript

//Syntax: string.padEnd(targetLength, padString)

//Example                                
let text = 'Hello';
console.log(text.padEnd(8, '!'));  // Output: 'Hello!!!'

Pads the current string from the beginning with another string until it reaches the desired length.

padStart(targetLength, padString)

 str = "5"   targetLength = 3   padString = "0"

 Before:   After:
 +---+     +-----------+
 | 5 |  ?  | 0 | 0 | 5 |
 +---+     +-----------+
  len=1     len=3  (padded at start)

javascript

//Syntax: string.padStart(targetLength, padString)

//Example                                
let text = '5';
console.log(text.padStart(3, '0'));  // Output: '005'

Repeats the string a specified number of times.

repeat(count)

 str = "Hi "   count = 3

 +----+   +----+   +----+
 | Hi | + | Hi | + | Hi |
 +----+   +----+   +----+
                |
                ?
        +----------------+
        |  Hi Hi Hi      |
        +----------------+

javascript

//Syntax: string.repeat(count)

//Example                                
let text = 'Hi ';
console.log(text.repeat(3));  // Output: 'Hi Hi Hi '

Replaces a specified value with another value in a string.

replace(searchValue, newValue)

 str = "Hello World"
  H  e  l  l  o     W  o  r  l  d
                    +------+
                    "World"  ?  "JavaScript"
                         |
                         ?
            "Hello JavaScript"

javascript

//Syntax: string.replace(searchValue, newValue)

//Example                                
let text = 'Hello World';
console.log(text.replace('World', 'JavaScript'));  // Output: 'Hello JavaScript'

Extracts a part of a string and returns it as a new string.

slice(start, end)

 str = "Hello World"
  +-------------------------------------------+
  | H | e | l | l | o |   | W | o | r | l | d |
  +-------------------------------------------+
    0   1   2   3   4   5   6   7   8   9  10
  start=0                 end=5
  +-------------------+
         "Hello"

 "Hello World".slice(0, 5)   ?  "Hello"
 "Hello World".slice(6)      ?  "World"  (to end)

javascript

//Syntax: string.slice(start, end)

//Example:                      
let text = 'Hello World';
console.log(text.slice(0, 5));  // Output: 'Hello'

Splits a string into an array of substrings based on a specified delimiter.

split(separator)

 str = "a,b,c"
  +-------------------+
  | a | , | b | , | c |
  +-------------------+
       ?       ?
   separator separator

 "a,b,c".split(",")  ?  ["a", "b", "c"]
 "Hello".split("")   ?  ["H","e","l","l","o"]

javascript

//Syntax: string.split(separator)

//Example:                      
let text = 'a,b,c';
console.log(text.split(','));  // Output: ['a', 'b', 'c']

Checks if a string starts with a specified substring.

startsWith(searchString)

 str = "Hello World"
  H  e  l  l  o     W  o  r  l  d
  +-----+
  "Hello"  ? match at start

 "Hello World".startsWith("Hello")  ?  true
 "Hello World".startsWith("World")  ?  false

javascript

//Syntax: string.startsWith(searchString)

//Example:                      
let text = 'Hello World';
console.log(text.startsWith('Hello'));  // Output: true

Extracts characters between two indices and returns a new string.

substring(start, end)

 str = "Hello World"
  +-------------------------------------------+
  | H | e | l | l | o |   | W | o | r | l | d |
  +-------------------------------------------+
    0   1   2   3   4   5   6   7   8   9  10
  start=0                 end=5
  +-------------------+
         "Hello"

 "Hello World".substring(0, 5)  ?  "Hello"
 "Hello World".substring(6)     ?  "World"

javascript

//Syntax: string.substring(start, end)

//Example:                      
let text = 'Hello World';
console.log(text.substring(0, 5));  // Output: 'Hello'

Converts a string to lowercase.

toLowerCase()

 str = "Hello World"
  +-------------------------------------------+
  | H | e | l | l | o |   | W | o | r | l | d |
  +-------------------------------------------+
    ?                       ?
  lowercase               lowercase
  +-------------------------------------------+
  | h | e | l | l | o |   | w | o | r | l | d |
  +-------------------------------------------+
 Result: "hello world"

javascript

//Syntax: string.toLowerCase()

//Example:                      
let text = 'Hello World';
console.log(text.toLowerCase());  // Output: 'hello world'

Converts a string to uppercase.

toUpperCase()

 str = "hello world"
  +-------------------------------------------+
  | h | e | l | l | o |   | w | o | r | l | d |
  +-------------------------------------------+
    ?                       ?
  uppercase               uppercase
  +-------------------------------------------+
  | H | E | L | L | O |   | W | O | R | L | D |
  +-------------------------------------------+
 Result: "HELLO WORLD"

javascript

//Syntax: string.toUpperCase()

//Example:                      
let text = 'hello world';
console.log(text.toUpperCase());  // Output: 'HELLO WORLD'

Removes whitespace from both ends of a string.

trim()

 str = "   Hello World   "
  +---------------------------------------+
  |   |   |   |  Hello World  |   |   |   |
  +---------------------------------------+
   ? whitespace             whitespace ?
   +--- removed -------------- removed +
                     |
                     ?
            +---------------+
            |  Hello World  |
            +---------------+

javascript

//Syntax: string.trim()

//Example:                      
let text = '   Hello World   ';
console.log(text.trim());  // Output: 'Hello World'

Removes whitespace from the end of a string.

trimEnd()

 str = "Hello World   "
  +---------------------------+
  |  Hello World  |   |   |   |
  +---------------------------+
                   ? whitespace
                   +--- removed +
                     |
                     ?
            +---------------+
            |  Hello World  |
            +---------------+

javascript

//Syntax: string.trimEnd()

//Example:                      
let text = 'Hello World   ';
console.log(text.trimEnd());  // Output: 'Hello World'

Removes whitespace from the beginning of a string.

trimStart()

 str = "   Hello World"
  +---------------------------+
  |   |   |   |  Hello World  |
  +---------------------------+
   ? whitespace
   +--- removed +
                     |
                     ?
            +---------------+
            |  Hello World  |
            +---------------+

javascript

//Syntax: string.trimStart()

//Example:                      
let text = '   Hello World';
console.log(text.trimStart());  // Output: 'Hello World'

Returns the primitive value of a string object.

valueOf()

 String Object:
  +-----------------------------+
  |  new String("Hello")        |
  |  (String wrapper object)    |
  +-----------------------------+
                |
                | .valueOf()
                ?
  +-----------------------------+
  |  "Hello"                    |
  |  (primitive string value)   |
  +-----------------------------+

javascript

//Syntax: string.valueOf()

//Example:                      
let strObj = new String('Hello');
console.log(strObj.valueOf());  // Output: 'Hello'
  • Strings are text values wrapped in quotes (', ", or backticks `).
  • Quotes must match: start with ' and end with ', or " with ".
  • Escape characters use a backslash (\) to include special characters like \n, \', \".
  • String literals are text typed directly in your code, not created via new String().
  • .length gives you the total character count, including spaces.
  • Indexing lets you access characters with [index], just like arrays.
  • Immutability means you can't change a string in place. You always create a new one.
  • String methods like .toUpperCase(), .slice(), and .split() return new strings and never modify the original.

What's next? Practice string methods in exercises and quizzes, then try combining multiple methods in one small task.

Videos for this topic will be added soon.