String
We already talked about working with strings, now let’s look at the String object provided by JavaScript.
The String object has one static method, String.fromCharCode()
, which is used to create a string representation from a sequence of Unicode characters. Here we build a simple string using the ASCII codes
You can also use octal or hexadecimal numbers:
All the other methods described here are instance methods, methods that are run on a string variable:
charAt(i)
charCodeAt(i)
codePointAt(i)
concat(str)
endsWith(str)
includes(str)
indexOf(str)
lastIndexOf(str)
localeCompare()
match(regex)
normalize()
padEnd()
padStart()
repeat()
replace(str1, str2)
search(str)
slice(begin, end)
split(separator)
startsWith(str)
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
trimEnd()
trimStart()
All methods are case sensitive and do not mutate the original string.
charAt(i)
charAt(i)
Return the character at the index i
Examples:
If you give an index that does not match the string, you get an empty string.
JavaScript does not have a “char” type, so a char is a string of length 1.
charCodeAt(i)
charCodeAt(i)
Return the character code at the index i
. Similar to charAt()
, except it returns the Unicode 16-bit integer representing the character:
Calling toString()
after that will return the hexadecimal number, which you can lookup in Unicode tables like this.
codePointAt(i)
codePointAt(i)
This was introduced in ES2015 to handle Unicode characters that cannot be represented by a single 16-bit Unicode unit, but need 2 instead.
Using charCodeAt()
you need to retrieve the first, and the second, and combine them. Using codePointAt()
you get the whole character in one call.
For example, this chinese character ”𠮷” is composed by 2 UTF-16 (Unicode) parts:
If you create a new character by combining those unicode characters:
You can get the same result usign codePointAt()
:
If you create a new character by combining those unicode characters:
concat(str)
concat(str)
Concatenates the current string with the string str
Example:
endsWith(str)
endsWith(str)
Check if a string ends with the value of the string str
.
includes(str)
includes(str)
Check if a string includes the value of the string str
.
includes()
also accepts an optional second parameter, an integer which indicates the position where to start searching for:
indexOf(str)
indexOf(str)
Gives the position of the first occurrence of the string str
in the current string. Returns -1 if the string is not found.
You can pass a second parameters to set the starting point:
lastIndexOf(str)
lastIndexOf(str)
Gives the position of the last occurrence of the string str
in the current string
localeCompare()
localeCompare()
This method compares a string to another, returning a number (negative, 0, positive) that tells if the current string is lower, equal or greater than the string passed as argument, according to the locale.
The locale is determined by the current locale, or you can pass it as a second argument:
The most common use case is for ordering arrays:
where one would typically use
with the difference that localeCompare() allows us to make this compatible with alphabets used all over the globe.
An object passed as third argument can be used to pass additional options. Look for all the possible values of those options on MDN.
match(regex)
match(regex)
Given a regular expression identified by regex
, try to match it in the string.
normalize()
normalize()
Unicode has four main normalization forms. Their codes are NFC
, NFD
, NFKC
, NFKD
. Wikipedia has a good explanation of the topic.
The normalize()
method returns the string normalized according to the form you specify, which you pass as parameter (NFC
being the default if the parameter is not set).
I will reuse the MDN example because I’m sure there is a valid usage but I can’t find another example:
padEnd()
padEnd()
The purpose of string padding is to add characters to a string, so it reaches a specific length.
padEnd()
, introduced in ES2017, adds such characters at the end of the string.
padStart()
padStart()
Like padEnd()
, we have padStart()
to add characters at the beginning of a string.
Sample usage:
repeat()
repeat()
Introduced in ES2015, repeats the strings for the specificed number of times:
Returns an empty string if there is no parameter, or the parameter is 0
. If the parameter is negative you’ll get a RangeError.
replace(str1, str2)
replace(str1, str2)
Find the first occurrence of str1
in the current string and replaces it with str2
(only the first!). Returns a new string.
You can pass a regular expression as the first argument:
replace()
will only replace the first occurrence, unless you use a regex as the search string, and you specify the global (/g
) option:
The second parameter can be a function. This function will be invoked for every match found, with a number of arguments:
the the string that matches the pattern
an integer that specifies the position within the string where the match occurred
the string
The return value of the function will replace the matched part of the string.
Example:
This also works for regular strings, not just regexes:
In case your regex has capturing groups, those values will be passed as arguments right after the match parameter:
search(str)
search(str)
Return the position of the first occurrence of the string str
in the current string.
It returns the index of the start of the occurrence, or -1 if no occurrence is found.
You can search using a regular expression (and in reality, even if you pass a string, that’s internally and transparently used as a regular expression too).
slice(begin, end)
slice(begin, end)
Return a new string from the part of the string included between the begin
and end
positions.
The original string is not mutated.
end
is optional.
If you set a negative first parameter, the start index starts from the end, and the second parameter must be negative as well, always counting from the end:
split(separator)
split(separator)
split()
truncates a string when it finds a pattern (case sensitive), and returns an array with the tokens:
startsWith(str)
startsWith(str)
Check if a string starts with the value of the string str
You can call startsWith()
on any string, provide a substring, and check if the result returns true
or false
:
This method accepts a second parameter, which lets you specify at which character you want to start checking:
substring()
substring()
substring()
returns a portion of a string and it’s similar to slice()
, with some key differences.
If any parameter is negative, it is converted to 0
. If any parameter is higher than the string length, it is converted to the length of the string.
So:
toLocaleLowerCase()
toLocaleLowerCase()
Returns a new string with the lowercase transformation of the original string, according to the locale case mappings.
The first parameter represents the locale, but it’s optional (and if omitted, the current locale is used):
As usual with internationalization we might not recognize the benefits, but I read on MDN that Turkish does not have the same case mappings at other languages, to start with.
toLocaleUpperCase()
toLocaleUpperCase()
Returns a new string with the uppercase transformation of the original string, according to the locale case mappings.
The first parameter represents the locale, but it’s optional (and if omitted, the current locale is used):
toLowerCase()
toLowerCase()
Return a new string with the text all in lower case.
Same as toLocaleLowerCase()
, but does not consider locales at all.
toString()
toString()
Returns the string representation of the current String object:
Same as valueOf()
.
toUpperCase()
toUpperCase()
Return a new string with the text all in lower case.
Same as toLocaleUpperCase()
, but does not consider locales at all.
trim()
trim()
Return a new string with removed white space from the beginning and the end of the original string
trimEnd()
trimEnd()
Return a new string with removed white space from the end of the original string
trimRight()
is an alias of this method.
trimStart()
trimStart()
Return a new string with removed white space from the start of the original string
trimLeft()
is an alias of this method.
Last updated
Was this helpful?