What is a String?
- The sequence of one or more characters enclosed within quotation marks is called a string.
- The quotation can be single quotes
''
or double quotes" "
or backtick ``. - And, the sequence of characters can be alphabets, numbers, symbols, etc.
Some commonly used JavaScript methods:
- Length
As the name suggests,
length
returns the length of the string.
Note, in the above example the whitespace, comma, and exclamation mark are also part of the string.
2.charAt(index)
- The
charAt()
returns the character at a specified index in a string. - The very first character of the string has an index of 0, the second character has index 1, and so on...
3.substring(start, end)
- This method extracts the part of the string between
start
andend
and returns the substring.
4.substr(start, length)
- The
substr()
method returns the specified number of characters from the specified index (start
parameter) from a given string. - Here,
start
defines the starting index from where the substring is to be extracted from the original string. - And,
length
defines the number of characters to be extracted from the specified start index. -
Note: If the
length
parameter isn't given, then all the characters from start till the end of the string are extracted.
5.concat()
- The
concat()
method joins two or more strings. - The
concat()
method doesn't modify the original strings, but it returns a new string.
6.toUpperCase()
- The
toUpperCase()
method converts the strings to upper case letters.
7.toLowerCase()
- The
toLowerCase()
method converts the strings to lower case letters.
8.slice(start, end)
- The
slice()
method extracts and returns a part of the string from start to (excluding) the end character. - If there's no second argument specified, then the slice method extracts till the end of the string.
-
slice()
also works on negative indices. If a negative index is specified, the string is extracted from the right end. - The negative index starts from -1 and it indicates the last character of the string, -2 is the second last character, and so on...
9.replace(substring)
- The
replace()
method is used to replace a part of a given string with a new substring. - One important thing to note here is that the
replace()
method does not change the original string on which it is called upon. It simply returns a new string.
10.includes(substring)
- The
includes()
method does a case-sensitive search on the original string to see if the specified substring is present in the string or not. - If the specified string is present, the method returns
true
otherwisefalse
.
11.trim()
- The
trim()
method removes leading and trailing whitespaces from the given string.
Conclusion
- That is all from my side. I hope this article provides you with the basics of some popular string methods used in JavaScript.
- Working through the examples is the best idea to understand these methods. Play with the examples.
Top comments (0)