⬅ Back

STRING METHODS IN JAVASCRIPT

This note explains string methods in simple language.

Strings are used everywhere in JavaScript:

Because of that, string methods are very important for front-end and full stack development.

1. Properties and methods

In programming, data has:

These together are part of the data’s interface.

A simple real-life idea:

In JavaScript:

Diagram 1. Properties vs methods

String
│
├─ Properties → describe data
│  └─ length
│
└─ Methods → do actions
   ├─ slice()
   ├─ toLowerCase()
   ├─ toUpperCase()
   ├─ includes()
   ├─ startsWith()
   ├─ endsWith()
   ├─ indexOf()
   └─ trim()

Explanation

A property gives information about the value.

A method performs an action and returns a result.

2. Properties

A property is a descriptive characteristic of an entity.

For strings, one important property is:

length

To access a property, JavaScript uses dot notation.

Syntax

objectName.property

Example

const message = "JavaScript is awesome";
console.log(message.length); // 21

Diagram 2. Accessing a property

message.length

1. message → the string
2. .length → ask for its length
3. result → number of characters

Explanation

The length property tells you how many characters are inside the string.

It counts:

3. Methods

A method is an action that belongs to data.

For strings, methods can do things like:

Syntax

objectName.method()

Example

const message = "JavaScript is awesome";
console.log(message.toUpperCase()); // "JAVASCRIPT IS AWESOME"

Diagram 3. Accessing a method

message.toUpperCase()

1. message → the string
2. .toUpperCase() → method call
3. result → new uppercase string

Explanation

A method looks similar to a property, but methods use parentheses () because they perform an action.

4. Property vs method

This difference is very important.

Property

message.length

No parentheses, because it is just information.

Method

message.toUpperCase()

With parentheses, because it performs an action.

Diagram 4. Property vs method syntax

Property:
value.length

Method:
value.toUpperCase()

Explanation

This is a basic JavaScript pattern you will use all the time.

5. Methods and properties need data

Methods and properties cannot exist alone.

You cannot use:

They must belong to some value.

Example

const text = "Hello";
console.log(text.length);
console.log(text.toUpperCase());

Diagram 5. Methods need an owner

Wrong idea:
trim()

Correct idea:
text.trim()

Explanation

A method belongs to the value before the dot.

6. The slice() method

The slice() method creates a copy of part of a string.

It does not change the original string.

Syntax

str.slice(startIndex, endIndex)

Where:

Diagram 6. How slice() works

slice(start, end)

Start index → included
End index   → not included

Explanation

This is one of the most important rules of slice():

7. slice() examples

const fullName = "Jacob Mercer";

console.log(fullName.slice(0, 4));  // "Jaco"
console.log(fullName.slice(3, 9));  // "ob Mer"
console.log(fullName.slice(0, fullName.length)); // "Jacob Mercer"

Diagram 7. slice(0, 4) on "Jacob Mercer"

String:  J a c o b   M e r c e r
Index:   0 1 2 3 4 5 6 7 8 9 10 11

slice(0, 4)
Take indexes: 0, 1, 2, 3
Result: "Jaco"

Explanation

Index 4 is not included, so the result ends before b.

8. slice() without endIndex

If endIndex is not given, JavaScript copies from startIndex to the end of the string.

Example

const fullName = "Jacob Mercer";

console.log(fullName.slice(1)); // "acob Mercer"
console.log(fullName.slice(3)); // "ob Mercer"

Diagram 8. slice() from one index to the end

slice(3)

Start at index 3
Keep copying to the end

Explanation

This is very useful when you want “everything from here onward”.

9. slice() with no arguments

If you call slice() with no arguments, it returns a full copy of the string.

Example

const fullName = "Jacob Mercer";
console.log(fullName.slice()); // "Jacob Mercer"

Diagram 9. slice() with no arguments

slice()

Copy the whole string

Explanation

This is not very common for simple learning tasks, but it is correct.

10. Saving slice() result in variables

const fullName = "Jacob Mercer";
const firstName = fullName.slice(0, 5);
const lastName = fullName.slice(6);

console.log(fullName);  // "Jacob Mercer"
console.log(firstName); // "Jacob"
console.log(lastName);  // "Mercer"

Diagram 10. Splitting a full name with slice()

"Jacob Mercer"

Indexes:
J a c o b _ M e r c e r
0 1 2 3 4 5 6 7 8 9 10 11

firstName = slice(0, 5) → "Jacob"
lastName  = slice(6)    → "Mercer"

Explanation

This is a practical example of extracting meaningful parts of a string.

11. The toLowerCase() method

toLowerCase() returns a new string where all letters are lowercase.

It does not change the original string.

Example

const message = "Welcome to Bahamas!";
console.log(message.toLowerCase()); // "welcome to bahamas!"
console.log(message); // "Welcome to Bahamas!"

Diagram 11. toLowerCase()

Original: "Welcome to Bahamas!"
Result:   "welcome to bahamas!"

Explanation

The original string stays the same.

The method returns a new string.

12. The toUpperCase() method

toUpperCase() returns a new string where all letters are uppercase.

It also does not change the original string.

Example

const message = "Welcome to Bahamas!";
console.log(message.toUpperCase()); // "WELCOME TO BAHAMAS!"
console.log(message); // "Welcome to Bahamas!"

Diagram 12. toUpperCase()

Original: "Welcome to Bahamas!"
Result:   "WELCOME TO BAHAMAS!"

Explanation

Again, the original string is unchanged.

13. Why changing case is useful

These methods are very useful when comparing user input.

Example problem:

console.log("saMsUng" === "samsung"); // false
console.log("saMsUng" === "SAMSUNG"); // false

Even though the text means the same brand, the comparison fails because string comparison is case-sensitive.

Diagram 13. Why case matters

"saMsUng" !== "samsung"
"saMsUng" !== "SAMSUNG"

Reason:
Different letter case

Explanation

JavaScript compares strings exactly, including uppercase and lowercase letters.

14. Normalizing strings with toLowerCase()

A common solution is to normalize both strings to one case.

Example

const brandName = "samsung";
const userInput = "saMsUng";
const lowercaseInput = userInput.toLowerCase();

console.log(brandName); // "samsung"
console.log(userInput); // "saMsUng"
console.log(userInput === brandName); // false
console.log(lowercaseInput); // "samsung"
console.log(lowercaseInput === brandName); // true

Diagram 14. Normalizing user input

User input: "saMsUng"
   ↓
toLowerCase()
   ↓
"samsung"
   ↓
compare with "samsung"
   ↓
true

Explanation

This is a very common real-world pattern in search, login, filtering, and validation.

15. The includes() method

The includes() method checks whether one string contains another string.

It returns:

Syntax

str.includes(substring)

Diagram 15. What includes() checks

Main string
   ↓
search for substring
   ↓
found? → true
not found? → false

Explanation

This method answers the question:

“Does this string contain that text?”

16. includes() examples

const username = "Jacob Mercer";

console.log(username.includes("Jacob"));  // true
console.log(username.includes("John"));   // false
console.log(username.includes("Mercer")); // true
console.log(username.includes("Doe"));    // false

Diagram 16. includes() examples

"Jacob Mercer".includes("Jacob")  → true
"Jacob Mercer".includes("John")   → false
"Jacob Mercer".includes("Mercer") → true
"Jacob Mercer".includes("Doe")    → false

Explanation

If the substring appears anywhere inside the main string, the result is true.

17. includes() is case-sensitive

Case matters here too.

const username = "Jacob Mercer";

console.log(username.includes("Jacob"));  // true
console.log(username.includes("jacob"));  // false
console.log(username.includes("Mercer")); // true
console.log(username.includes("mercer")); // false

Diagram 17. Case-sensitive search

"Jacob Mercer".includes("Jacob") → true
"Jacob Mercer".includes("jacob") → false

Explanation

Uppercase and lowercase are treated as different characters.

18. Using includes() in real code

const message = "Please buy our stuff!";
const hasSpam = message.includes("buy");

if (hasSpam) {
  console.log("Warning: This message contains forbidden words.");
} else {
  console.log("You can safely open this message.");
}

Diagram 18. Spam check with includes()

message.includes("buy")
   ↓
true
   ↓
show warning

Explanation

This is a real use case: checking if text contains a forbidden word.

19. The startsWith() method

startsWith() checks whether a string begins with a given substring.

Syntax

str.startsWith(substr)

Example

const str = "Hello, world!";

console.log(str.startsWith("Hello")); // true
console.log(str.startsWith("hello")); // false

Diagram 19. startsWith()

"Hello, world!"
Starts with "Hello" → true
Starts with "hello" → false

Explanation

It checks only the beginning of the string.

20. The endsWith() method

endsWith() checks whether a string ends with a given substring.

Syntax

str.endsWith(substr)

Example

const str = "Hello, world!";

console.log(str.endsWith("world!")); // true
console.log(str.endsWith("World!")); // false

Diagram 20. endsWith()

"Hello, world!"
Ends with "world!" → true
Ends with "World!" → false

Explanation

It checks only the end of the string.

21. Important notes about startsWith() and endsWith()

Both methods are:

Also:

Diagram 21. Important rules for start/end checks

startsWith() and endsWith()
│
├─ case-sensitive
├─ return Boolean
└─ no argument → false

Explanation

These methods are very useful for checking prefixes and suffixes.

22. The indexOf() method

indexOf() finds the first position of a substring inside a string.

It returns:

Syntax

str.indexOf(substr)

Diagram 22. What indexOf() returns

Found substring    → return index
Not found          → return -1

Explanation

This method gives you the position, not just true/false.

23. indexOf() example

const message = "Welcome to Bahamas!";
const index = message.indexOf("to");
console.log(index); // 8

Diagram 23. indexOf("to")

"Welcome to Bahamas!"

Indexes:
W e l c o m e _ t o _ B a h a m a s !
0 1 2 3 4 5 6 7 8 9 ...

"to" starts at index 8

Explanation

indexOf() returns the index of the first character of the found substring.

24. indexOf() when nothing is found

const message = "Welcome to Bahamas!";
const index = message.indexOf("hello");
console.log(index); // -1

Diagram 24. Not found result

Search: "hello"
Found? no
Result: -1

Explanation

-1 means “not found”.

This is a very common JavaScript pattern.

25. Important details about indexOf()

Diagram 25. indexOf() summary

indexOf()
│
├─ first match only
├─ returns position
└─ returns -1 if not found

Explanation

Use indexOf() when you need the location of text inside a string.

26. The trim() method

trim() removes spaces from:

It does not remove spaces in the middle.

Syntax

str.trim()

Diagram 26. What trim() removes

Before: "   Hello world   "
After:  "Hello world"

Explanation

Only outer spaces are removed.

27. trim() example

const input = " JavaScript is awesome!    ";
const trimmedInput = input.trim();

console.log(trimmedInput); // "JavaScript is awesome!"
console.log(input); // " JavaScript is awesome!    "

Diagram 27. trim() does not change the original

Original string
" JavaScript is awesome!    "

trim()
   ↓

New string
"JavaScript is awesome!"

Explanation

Like many string methods, trim() returns a new string and leaves the original unchanged.

28. Why trim() is useful

trim() is especially useful for user input.

Example problem:

A user types:

"   Nikita   "

But you want:

"Nikita"

This is common in:

Diagram 28. Real user input cleaning

User types:
"   exemple@nikitagoluban.eu   "

trim()
   ↓
"exemple@nikitagoluban.eu"

Explanation

This helps remove accidental spaces before checking or saving data.

29. String methods do not usually change the original string

This is one of the most important ideas in this topic.

Methods like:

return new strings.

They do not change the original string.

Diagram 29. Original stays the same

Original string
   ↓
call method
   ↓
new result string

Original remains unchanged

Explanation

If you want to keep the changed result, save it in a variable.

30. Chaining methods together

You can combine methods.

Example

const userInput = "   SaMsUnG   ";
const normalized = userInput.trim().toLowerCase();

console.log(normalized); // "samsung"

Diagram 30. Method chaining

"   SaMsUnG   "
   ↓ trim()
"SaMsUnG"
   ↓ toLowerCase()
"samsung"

Explanation

This is very useful in real applications.

31. Practical example: email check

const email = "  exemple@nikitagoluban.eu  ";
const cleanedEmail = email.trim().toLowerCase();

console.log(cleanedEmail); // "exemple@nikitagoluban.eu"

Diagram 31. Cleaning email input

Raw input:
"  exemple@nikitagoluban.eu  "

1. trim()
2. toLowerCase()

Result:
"exemple@nikitagoluban.eu"

Explanation

This is a very realistic example from full stack development.

32. Practical example: checking file type

const fileName = "photo.jpg";

console.log(fileName.endsWith(".jpg")); // true
console.log(fileName.endsWith(".png")); // false

Diagram 32. File extension check

"photo.jpg"
Ends with ".jpg" → true
Ends with ".png" → false

Explanation

endsWith() is often used to check file extensions.

33. Practical example: checking URL or route

const route = "/profile/settings";

console.log(route.startsWith("/profile")); // true
console.log(route.startsWith("/admin"));   // false

Diagram 33. Route prefix check

"/profile/settings"
Starts with "/profile" → true
Starts with "/admin"   → false

Explanation

startsWith() is very useful for checking prefixes.

34. Practical example: finding text position

const sentence = "I love JavaScript";
console.log(sentence.indexOf("Java")); // 7

Diagram 34. Finding substring position

"I love JavaScript"

Indexes:
I _ l o v e _ J a v a S c r i p t
0 1 2 3 4 5 6 7 ...

"Java" starts at 7

Explanation

Use indexOf() when you need the exact position.

35. Practical example: safe search with normalization

const productName = "Samsung Galaxy";
const userSearch = "   sAmSuNg   ";

const normalizedSearch = userSearch.trim().toLowerCase();
const normalizedProduct = productName.toLowerCase();

console.log(normalizedProduct.includes(normalizedSearch)); // true

Diagram 35. Better text search

User search:
"   sAmSuNg   "
   ↓ trim()
"sAmSuNg"
   ↓ toLowerCase()
"samsung"

Product:
"Samsung Galaxy"
   ↓ toLowerCase()
"samsung galaxy"

includes("samsung") → true

Explanation

This is a very good real-world pattern for search features.

36. Common beginner mistakes

Mistake 1. Forgetting parentheses on methods

Wrong:

message.toUpperCase

Correct:

message.toUpperCase()

Mistake 2. Thinking methods change the original string

Wrong idea:

const text = "Hello";
text.toUpperCase();
console.log(text); // still "Hello"

Correct way:

const text = "Hello";
const upper = text.toUpperCase();
console.log(upper); // "HELLO"

Mistake 3. Forgetting case sensitivity

console.log("Jacob".includes("jacob")); // false

Different case means not equal.

Mistake 4. Misunderstanding slice() end index

const word = "JavaScript";
console.log(word.slice(0, 4)); // "Java"

End index 4 is not included.

Mistake 5. Thinking trim() removes spaces in the middle

const text = "Hello   world";
console.log(text.trim()); // "Hello   world"

Only outer spaces are removed.

Diagram 36. Common mistakes

1. Methods need ()
2. Most string methods return new strings
3. Search methods are case-sensitive
4. slice() excludes end index
5. trim() removes only outer spaces

Explanation

These are the mistakes beginners make very often, so they are worth remembering.

37. When to use each method

slice()

Use when you want part of a string.

toLowerCase() / toUpperCase()

Use when you want to normalize case.

includes()

Use when you want to know if a substring exists.

startsWith()

Use when you want to check the beginning.

endsWith()

Use when you want to check the end.

indexOf()

Use when you need the position of a substring.

trim()

Use when you want to remove outer spaces.

Diagram 37. Method choice map

Need part of a string?       → slice()
Need lowercase/uppercase?    → toLowerCase() / toUpperCase()
Need true/false contains?    → includes()
Need start check?            → startsWith()
Need end check?              → endsWith()
Need position?               → indexOf()
Need remove outer spaces?    → trim()

Explanation

This is a practical “which method should I use?” guide.

38. Full summary

Property

A characteristic of data, for example length.

Method

An action that belongs to data, for example toUpperCase().

length

Returns the number of characters in a string.

slice(start, end)

Returns part of a string from start to before end.

toLowerCase()

Returns a lowercase version of the string.

toUpperCase()

Returns an uppercase version of the string.

includes(substring)

Checks whether a substring exists in the string.

startsWith(substr)

Checks whether a string starts with a substring.

endsWith(substr)

Checks whether a string ends with a substring.

indexOf(substr)

Returns the index of the first occurrence, or -1.

trim()

Removes spaces from the beginning and end of a string.

Diagram 38. Final map of string methods

String methods
│
├─ length
├─ slice()
├─ toLowerCase()
├─ toUpperCase()
├─ includes()
├─ startsWith()
├─ endsWith()
├─ indexOf()
└─ trim()

Explanation

These are some of the most useful beginner string tools in JavaScript.

39. Revision block

1. Properties describe data
2. Methods perform actions on data
3. length gives string length
4. slice() returns part of a string
5. toLowerCase() makes letters lowercase
6. toUpperCase() makes letters uppercase
7. includes() checks if text exists inside a string
8. startsWith() checks the beginning
9. endsWith() checks the end
10. indexOf() gives the first found position or -1
11. trim() removes spaces from the beginning and end
12. Most string methods return new strings and do not change the original

40. Final conclusion

String methods are one of the foundations of practical JavaScript.

If you understand:

then you already have a strong base for handling text in real applications.

These methods are used everywhere in full stack development:

⬅ Back