Here's a cheatsheet of the latest ECMAScript string methods in Markdown format:
-
String.prototype.at(index: number)
Will get character at certain index in a string.
'hello'.at(0)
Results: 'h'
-
String.prototype.charAt(index: number)
Returns the character at a specified index (position) in a string.
'hello'.charAt(0)
Results: 'h'
-
String.prototype.charCodeAt(index: number)
Returns the code of the character at a specified index in a string.
'hello'.charCodeAt(0)
Results: 72
(The Unicode of 'H')
-
String.prototype.padStart(targetLength: number, padString: string)
Pads another string (multiple times) until the resulting string reaches the given length.
'5'.padStart(4, '0')
Results: '005'
-
String.prototype.padEnd(targetLength: number, padString: string)
Pads another string (multiple times) until it reaches a given length.
'5'.padEnd(4, '0')
Results: '5000'
-
String.prototype.repeat(count: number)
Returns a new string with a specified number of copies of the string it was called on.
'hello'.repeat(2)
Results: 'hellohello'
-
String.prototype.trim()
Removes whitespace from both sides of a string.
' Hello World '.trim()
Results: 'Hello World'
-
String.prototype.trimStart()
Removes whitespace only from the start of a string.
' Hello World '.trimStart()
Results: 'Hello World '
-
String.prototype.trimEnd()
Removes whitespace only from the end of a string.
' Hello World '.trimEnd()
Results: ' Hello World'
-
String.prototype.replace(searchValue: string | RegExp, replacement: string | (substring: string, ...args: any[]) => string)
Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
'Hello World'.replace('World', 'there')
Results: 'Hello there'
-
String.prototype.match(regexp: RegExp)
Searches a string for a match against a regular expression, and returns the matches.
'The rain in SPAIN stays mainly in the plain'.match(/ain/gi)
Results: ['ain', 'AIN', 'ain', 'ain']
-
String.prototype.search(regexp: RegExp)
Searches a string for a specified value, or regular expression, and returns the position of the match.
'Hello World'.search('World')
Results: 6
-
String.prototype.slice(start?: number, end?: number)
Extracts a part of a string and returns the extracted part in a new string.
'Apple, Banana, Kiwi'.slice(7, 13)
Results: 'Banana'
-
String.prototype.split(separator?: string | RegExp, limit?: number)
Splits a string into an array of substrings.
'How are you doing today?'.split(' ')
Results: ['How', 'are', 'you', 'doing', 'today?']
Top comments (0)