# Functions Available for Use on a JavaScript String

June 14, 2020 200

JavaScript strings are used to store a sequence of characters. They can be created as primitives as well as objects. They are written inside a double quote or a single quote. There are many operations that you can perform on strings, for example, search whether a sequence of characters is present in a string or not, converting letters in a string to uppercase or lowercase, etc. Let us discuss them in detail with examples.

## includes()

The includes() method finds out whether a sequence of characters is present in the string or not. It returns true if a sequence of characters is found, otherwise, it returns false. The syntax is string.includes(characters, start). The optional start parameter (default value is 0) represents the starting position of the search. Consider the following example.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.includes("very")
console.log(result)


### Output

true

The string “str” contains the sequence of characters “very”, hence, the method returns true.

## search()

The search() method returns the index of a pattern in a string. It returns the index of the first occurrence of the pattern. If the pattern is not found, it returns -1. The syntax is string.search(regExp). Note that you can either provide a string or a regular expression. In the case of a string, the method converts it into a regular expression. Check the example below.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.search("in")
console.log(result)


### Output

14

This method takes a string “in” and finds its index. Note that since the string is provided, it will be implicitly converted into a regular expression. There are two places where “in” occurs, the method only returns the index of the first occurrence i.e. 14. Let’s see another example.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.search("/f.*z/g")
console.log(result)


### Output

-1

The above search is for a pattern that starts with “f” followed by any character and ends with “z”. No such pattern is present in the string, therefore, the method returns -1.

## indexOf()

The indexOf() method returns the index of the first appearance of a sequence of characters in a string. It returns -1 if the sequence of characters is not found. The syntax is string.indexof(characters, start). The optional start parameter (default value is 0) represents the starting position of the search. Let’s see.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.indexOf("in")
console.log(result)


### Output

14

You can observe that the example and output are the same as given in the first example of the search() method. So, what is the difference? Note that the search method takes a regular expression as a parameter, while the indexOf() takes a string. Moreover, it has an additional parameter start that allows you to specify the starting position of the search.

## lastIndexOf()

This method performs a similar task as the indexOf() method, but it searches the string backward from the starting position(default value = length of the array – 1) i.e. it returns the position of the last appearance of the given sequence of characters.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.lastIndexOf("in")
console.log(result)


### Output

28

As we have already observed there are two places where “in” occurs. The indexOf() method finds the index of the first appearance, and the lastIndexOf() finds the index of the last appearance i.e. 28.

## match()

This method takes a regular expression and matches the string against the given regular expression. It returns an array object containing the matches or null if no match is found. The syntax is string.match(regExp). If you pass a string as a parameter, it will implicitly convert it into a regular expression. Note that to find all the matches use the /g flag in the regular expression. Let us see how this works.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.match("/in/g")
console.log(result)


### Output

[‘in’, ‘in’]

It returns an array of the found matches.

Let’s what happens when we pass a string.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.match("in")
console.log(result)


### Output

[‘in’, index: 14, input: ‘Learn programming languages in a very simple way from CodesDope’ groups: undefined]

You can see that the method returns some different output and it only returns the first match. Therefore, the preferred way is to use regular expressions.

## replace()

This method takes a string or a regular expression, finds a match and replaces it with another provided string. If a string is provided, then it will only replace the first match. For regular expression, use /g flag to replace all matches. If the match is not found, it keeps the string unchanged. The syntax is string.replace(str|regExp, newstr|function). You can also provide a callback function to replace the matched sequence of characters. Consider the following example.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.replace("/very|way/g, x=>x.slice(1)")
console.log(result)


### Output

Learn programming languages in a ery simple ay from CodesDope

This method finds the word “very” or “way” and uses a function which in turn uses a slice method on the matched word to omit the first character. Hence, the words become “ery” and “ay”.

## slice()

The slice() method takes out selected characters from the original string and puts them into a new string. The syntax is string.slice(start, end). It extracts characters from the start position to the end – 1(inclusive) position. The length of the new string will be end – start. Consider the following examples.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.slice(6, 17)
console.log(result)


### Output

programming

This example extracts the word “programming” starting at index 6 and ending at 16.

The parameters start and end can also contain negative values to slice from the end of the string. Let’s see how this works.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.slice(-14, -10)
console.log(result)


### Output

from

This example extracts the word “from” starting at index -14 and ending at -11.

Note that both parameters are optional. If the start parameter is omitted, it is set to 0 and if the end parameter is omitted, it is set to the length of the string. If only one parameter is provided, it is considered as the start parameter. If both parameters are omitted, the whole string is sliced out. If the start is negative and greater than the string.length, it is set to 0.

## substr()

The substr() method takes out selected characters from the original string and put them into a new string. The syntax is string.substr(start, length). It starts extracting characters from the start position up to the length provided. Consider the following example.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.substr(6, 11)
console.log(result)


### Output

programming

The substr() starts extracting from position 6 till the length becomes 11 i.e. “programming”. You can also use a negative value for the start parameter to extract from the end.

Just like the slice() method, both parameters are optional. If both parameters are omitted, the whole string is taken out. If the length parameter is omitted, it is set to string.length-start. If only one parameter is provided, it is considered as the start parameter.

## substring()

This method is similar to the slice() method except it does not accept negative values for the start and end parameters. An Additional difference is that if the value of the start parameter is greater than the end parameter, the two values are swapped. The slice() method returns an empty string in this case.

## split()

The split() method separates a string into an array of substrings based on a separator given as a parameter. The syntax is split(separator, length). The optional length parameter sets the length of the array. The rest of the substrings will be omitted if the limit has been reached. Let’s see.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.split(" ")
console.log(result)


### Output

[‘Learn’, ’programming’, ’languages’, ’in’, ’a’, ’very’, ’simple’, ‘way’, ’from’, ’CodesDope’]

This method splits the string into an array based on the separator “ ”(space) i.e. the sequence of characters before space is considered one element and after it is considered another.

• It can be a string or a regular expression.
• If it is omitted or is not present in the string, the method returns an array containing the whole string as a single element.
• If the separator is an empty string i.e. “”, each element of an array contains a single character of the string.
• If the separator is found at the start of a string, the first element of an array will contain an empty string. i.e.
str = " Learn programming languages in a very simple way from CodesDope"
result = str.split(" ")
console.log(result)

Output
[‘’, ‘Learn’, ’programming’, ’languages’, ’in’, ’a’, ’very’, ’simple’, ‘way’, ’from’, ’CodesDope’]
• If the separator is found at the end of a string, the last element of an array will contain an empty string.

## startsWith()

This method finds out whether a string starts with a sequence of characters or not. It will return true if the condition is true, otherwise, it will return false. The syntax is string.startsWith(characters, start). The optional start parameter (default value is 0) represents the starting position of the search. Let’s see.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.startsWith("Learn")
console.log(result)


### Output

true

## endsWith()

This method finds out whether a string ends with a sequence of characters or not. It will return true if the condition is true, otherwise, it will return false. The syntax is string.endsWith(characters, length). The optional length parameter (default value is string.length) represents the length of the string to be used for searching.

## repeat()

The repeat() method repeats a string a given number of times and returns it as a new string. The syntax is string.repeat(RepNum).

str = "Learn programming languages in a very simple way from CodesDope\n"
result = str.repeat(3)
console.log(result)


### Output

Learn programming languages in a very simple way from CodesDope Learn programming languages in a very simple way from CodesDope Learn programming languages in a very simple way from CodesDope

## concat()

The concat() method concatenates two or more strings. The syntax is string1.concat(string2, string3, ….., stringN). It returns a new string that starts from string1 followed by the strings given as parameters. Consider the example below.

str1 = "Learn programming languages "
str2 = "in a very simple way "
str3 = "from CodesDope"
result = str1.concat(str2, str3)
console.log(result)


### Output

Learn programming languages in a very simple way from CodesDope

## charAt()

This method finds the character at a given index. The syntax is string.chartAt(index). If the index is negative or greater than string.length-1, the method returns an empty string. Check the example below.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.charAt(3)
console.log(result)


### Output

r

## charCodeAt()

This method is similar to the charAt() method except it returns the Unicode number of the character. It returns NaN if the index is negative or greater than string.length-1.

## fromCharCode()

This static method returns character(s) from the Unicode number(s). The syntax is String.fromCharCode(num1, num2, ….., numN).

result = String.fromCharCode(114, 116)
console.log(result)


### Output

rt

## localeCompare()

The localeCompare() method compares the strings based on the sort order. The syntax is string1.localeCompare(string2). It returns 1 if the string1 comes after string2 in the sort order. It returns -1 if the string1 comes before string2 and 0 if both strings have the same sort order. String1 is sometimes referred to as the reference string and string2 is referred to as the compare string. Consider the following example.

str1 = "abcdef"
str2 = "bacdef"
result = "str1.localeCompare(str2)"
console.log(result)


### Output

-1

Since the string “str2” comes after the string “str1” in the sort order (‘b’ comes after ‘a’), the output is -1.

## toLowerCase()

This method converts each letter in a string to lowercase. The syntax is string.toLowerCase(). It returns a new string with lowercase letters.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.toLowercase()
console.log(result)


### Output

learn programming languages in a very simple way from codesdope

## toUpperCase()

This method converts each letter in a string to uppercase. The syntax is string.toUpperCase(). It returns a string with uppercase letters.

str = "Learn programming languages in a very simple way from CodesDope"
result = str.toUppercase()
console.log(result)


### Output

LEARN PROGRAMMING LANGUAGES IN A VERY SIMPLE WAY FROM CODESDOPE

## toLocaleLowerCase()

This method is similar to the toLowerCase() method except it uses a specific locale to convert to lowercase letters. The syntax is string.toLocaleLowerCase(locale). The locale parameter is optional and it is a BCP 47 language tag or an array of these tags. The default value is the host’s current environment locale.

## toLocaleUpperCase

This method is similar to the toUpperCase() method except it uses a specific locale to convert to uppercase letters. The syntax is string.toLocaleUpperCase(locale).

## toString()

The toString() method returns the string representation of the given object. The syntax is string.toString(). Consider the following example.

str = new String("Learn programming languages in a very simple way from CodesDope")
result = str.toString()
console.log(result)


### Output

Learn programming languages in a very simple way from CodesDope

This method can be used for typecasting, for example, convert a number to a string.

## trim()

The trim() method removes white spaces from the beginning and the end of the string. The syntax is string.trim(). Let’s see.

str = "\n\tLearn programming languages in a very simple way from CodesDope    "
result = str.trim()
console.log(result)


### Output

Learn programming languages in a very simple way from CodesDope

## valueOf()

The valueOf() method in JavaScript returns the primitive value of the object. In the case of string objects, it returns the value of the String object and in the case of string literals, it returns itself. The following example finds the primitive value of a String object.

str = new String("Learn programming languages in a very simple way from CodesDope")
result = str.valueOf()
console.log(result)


### Output

Learn programming languages in a very simple way from CodesDope

Liked the post?
A computer science student having interest in web development. Well versed in Object Oriented Concepts, and its implementation in various projects. Strong grasp of various data structures and algorithms. Excellent problem solving skills.
Editor's Picks
0 COMMENT