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 a sequence of text in JavaScript. It can contain letters, numbers, symbols, spaces, or any combination of these characters. Strings are commonly used to store names, messages, sentences, and other text-based data. You can create a string by wrapping the text inside single quotes (' '), double quotes (" "), or backticks (` `), depending on your needs.

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.

Use the .length property to count the total number of characters in a string. It includes letters, numbers, symbols, and spaces. .length returns the total character count as a number.

JavaScript length

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 individual characters in a string using their index. Indexing starts at 0, so the first character is always at position 0.

JavaScript string array

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, which means you cannot change individual characters directly. To modify a string, create and assign a new string instead.

JavaScript string immutability

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 the specified index in a string. Every character in a JavaScript string has a unique position called an index, and indexing always starts from 0. This method looks at the index you provide and returns the character stored at that position without changing the original string. If the specified index is outside the valid range (less than 0 or greater than the last character's index), it returns an empty string instead of causing an error. The charAt() method is useful when you need to access a single character for checking, displaying, or processing text in your program.

JavaScript charAt

javascript

//Syntax: string.charAt(index)

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

Joins two or more strings into a single string. This method combines the original string with one or more additional strings without modifying the original value. It returns a new string containing all the joined text in the same order they are provided. The concat() method is useful when you need to merge names, sentences, messages, or other pieces of text into one complete string. Although string concatenation can also be done using the + operator or template literals, concat() provides a dedicated method for combining strings.

JavaScript concat

javascript

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

Checks whether a string ends with the specified substring. It returns true if the string ends with the given text, otherwise it returns false. This method performs the check without changing the original string and is useful for validating file extensions, URLs, words, or other text that must end with a specific value.

JavaScript endsWith

javascript

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

Checks whether a string contains the specified value. It returns true if the given text is found anywhere within the string, otherwise it returns false. This method does not modify the original string and is commonly used to search for words, phrases, or specific characters before performing further operations.

JavaScript includes

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 the specified value in a string. String indexing starts from 0, so the returned number represents the position where the value is first found. If the specified value does not exist in the string, the method returns -1. This method is commonly used to locate words, characters, or substrings before performing operations such as validation, extraction, or replacement.

JavaScript indexOf

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 the specified value in a string. Unlike indexOf(), this method searches from the end of the string but still returns the actual index position. If the specified value is not found, it returns -1. This method is useful when a value appears multiple times and you need the position of its final occurrence.

JavaScript indexOf

javascript

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

Searches a string for a match using a regular expression and returns the matching result. It can find patterns such as words, numbers, special characters, or custom text formats within a string. If a match is found, the method returns the matched value or related information; otherwise, it returns null. This method is commonly used for pattern matching, text validation, and extracting specific parts of a string.

JavaScript indexOf

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 specified length. If the original string is already equal to or longer than the target length, no padding is added. This method returns a new string without modifying the original one and is commonly used to format text, create fixed-length strings, or align output by adding characters such as spaces, zeros, or custom symbols at the end.

JavaScript indexOf

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 specified length. If the original string is already equal to or longer than the target length, no padding is added. This method returns a new string while keeping the original string unchanged and is commonly used to format values, add leading zeros, create fixed-length strings, or align text by inserting characters such as spaces, zeros, or custom symbols at the beginning.

JavaScript indexOf

javascript

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

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

Repeats the current string the specified number of times and returns a new string containing all the repeated copies. The original string remains unchanged after the operation. This method is useful for generating repeated patterns, creating separators, formatting output, or producing text multiple times without writing the same string repeatedly.

JavaScript indexOf

javascript

//Syntax: string.repeat(count)

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

Replaces the first occurrence of a specified value in a string with another value and returns a new string. The original string is not modified during the operation. This method can replace text using either a string or a regular expression, making it useful for updating words, correcting text, formatting data, or modifying specific parts of a string.

JavaScript indexOf

javascript

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

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

Extracts a portion of a string and returns it as a new string without changing the original string. You can specify the starting index and, optionally, the ending index to define which characters should be extracted. This method is useful for retrieving specific words, characters, or sections of text from a larger string for further processing or display.

JavaScript indexOf

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 using a specified delimiter, such as a space, comma, or any other character. The original string remains unchanged, and a new array is returned containing each separated part. This method is commonly used to break sentences into words, parse comma-separated values, or process text by dividing it into smaller, manageable pieces.

JavaScript indexOf

javascript

//Syntax: string.split(separator)

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

Checks whether a string starts with the specified substring. It returns true if the string begins with the given text, otherwise it returns false. This method does not modify the original string and is useful for validating prefixes, checking file names, URLs, commands, or verifying that a string begins with a specific value.

JavaScript indexOf

javascript

//Syntax: string.startsWith(searchString)

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

Extracts characters between the specified start and end indices and returns them as a new string. The original string remains unchanged after the operation. This method is useful for retrieving a specific portion of text based on character positions, such as extracting words, codes, or other sections of a string for further processing.

JavaScript indexOf

javascript

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

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

Converts all uppercase characters in a string to lowercase and returns a new string. The original string is not modified during the operation. This method is commonly used for case-insensitive comparisons, normalizing user input, searching text, or ensuring consistent formatting throughout an application.

JavaScript indexOf

javascript

//Syntax: string.toLowerCase()

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

Converts all lowercase characters in a string to uppercase and returns a new string. The original string remains unchanged after the conversion. This method is commonly used to emphasize text, standardize formatting, perform case-insensitive comparisons, or display content in a consistent uppercase format.

JavaScript indexOf

javascript

//Syntax: string.toUpperCase()

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

Removes whitespace from both the beginning and the end of a string while leaving the original string unchanged. It only removes leading and trailing spaces, tabs, and other whitespace characters, not the spaces between words. This method is commonly used to clean user input, validate text, and ensure consistent string formatting before processing or storing data.

JavaScript indexOf

javascript

//Syntax: string.trim()

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

Removes whitespace from the end of a string and returns a new string without modifying the original one. It removes trailing spaces, tabs, and other whitespace characters while keeping the content at the beginning and between words unchanged. This method is useful for cleaning user input, formatting text, and ensuring consistent string values before further processing.

JavaScript indexOf

javascript

//Syntax: string.trimEnd()

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

Removes whitespace from the beginning of a string and returns a new string without modifying the original one. It removes leading spaces, tabs, and other whitespace characters while keeping the rest of the string unchanged. This method is useful for cleaning user input, formatting text, and ensuring consistent string values before processing or displaying them.

JavaScript indexOf

javascript

//Syntax: string.trimStart()

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

Returns the primitive string value stored inside a String object. It converts a String object into its plain string representation without changing the original value. This method is rarely used in everyday JavaScript but can be helpful when working with String objects instead of primitive strings and you need to retrieve the underlying text value.

JavaScript indexOf

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.

Reviewed by

SimplyJavaScript Editorial Team

Technical editors and JavaScript educators with hands-on experience building frontend projects, writing learning material, and reviewing tutorials for clarity, accuracy, and beginner-friendly guidance.