String Methods In JavaScript
1. trim()
Method
The trim()
method removes whitespace (spaces, tabs, newlines) from both ends of a string, but not from the middle of the string. It is useful for cleaning up user input or string data.
- Note*: It doesn’t change the original string; it returns a new string with the whitespace removed.*
2. Strings are Immutable in JavaScript
In JavaScript, strings are immutable, meaning once a string is created, it cannot be changed or modified. Any operation that seems to modify a string (e.g., concatenation, replacing characters) actually returns a new string rather than modifying the original.
If you need to "change" a string, you must create a new one:
3. toUpperCase()
and toLowerCase()
toUpperCase()
converts all the characters in a string to uppercase.toLowerCase()
converts all characters in a string to lowercase.
Both methods return a new string; they do not modify the original string.
4. Method with Arguments: indexOf()
The indexOf()
method returns the index (position) of the first occurrence of a specified value in a string. It can take two arguments:
The value to search for.
(Optional) The position from which to start the search.
If the value is not found, it returns -1
.
5. Method Chaining
Method chaining allows you to call multiple methods on the same string in a single line. Each method returns a new string, so you can apply additional methods to that result.
6. slice()
Method
The slice()
method extracts a part of a string and returns it as a new string. It takes two arguments:
The starting index (inclusive).
The ending index (exclusive).
If you omit the second argument, it slices to the end of the string. Negative indices can be used to count from the end of the string.
7. replace()
and repeat()
replace()
: This method searches for a substring in a string and replaces it with another substring. It only replaces the first occurrence unless a regular expression with the global (g
) flag is used.
repeat()
: This method repeats a string a specified number of times and returns a new string with the repeated content.
Practice
Qs. For the Give String :
let msg = "help!";
Trim it & convert it to uppercase.
Qs. For the
String -> let name = "IndianArmy",
predict the output for following :
name.slice(4, 9) → anArm**name.indexOf("an") → 4name.replace("Indian", "Our") →** OurArmy