String methods in javascript
The string object in javascript comes with a bunch of built-in methods that are useful when working this this type of data. So let’s take a look at the main methods and learn a bit about them.
concat( )
The concat()
method concatenates the string arguments to the calling string and returns a new string.
endsWith( )
The endsWith()
method determines whether a string ends with the characters of a specified string, returning true
or false
as appropriate.
includes( )
The includes()
method performs a case-sensitive search to determine whether one string may be found within another string, returning true
or false
as appropriate.
indexOf( )
The indexOf()
method returns the index within the calling String
object of the first occurrence of the specified value, starting the search at fromIndex
. Returns -1
if the value is not found.
lastIndexOf( )
The lastIndexOf()
method returns the index within the calling String
object of the last occurrence of the specified value, searching backwards from fromIndex
. Returns -1
if the value is not found.
repeat( )
The repeat()
method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
replace( )
The replace()
method returns a new string with some or all matches of a pattern
replaced by a replacement
. The pattern
can be a string or a RegExp
, and the replacement
can be a string or a function to be called for each match. If pattern
is a string, only the first occurrence will be replaced.
slice( )
The slice()
method extracts a section of a string and returns it as a new string, without modifying the original string.
split( )
The split()
method divides a String
into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.
startsWith( )
The startsWith()
method determines whether a string begins with the characters of a specified string, returning true
or false
as appropriate.
substring( )
The substring()
method returns the part of the string
between the start and end indexes, or to the end of the string.
toLowerCase( )
The toLowerCase()
method returns the calling string value converted to lower case.
toUpperCase( )
The toUpperCase()
method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one).
trim( )
The trim()
method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)
trimEnd( )
The trimEnd()
method removes whitespace from the end of a string. trimRight()
is an alias of this method.
trimStart( )
The trimStart()
method removes whitespace from the beginning of a string. trimLeft()
is an alias of this method.