JavaScript Strings Methods and Properties

Photo by Joan Gamell on Unsplash

JavaScript Strings Methods and Properties

·

15 min read

Introduction

In JavaScript just like in so many other programming languages different data types are stored in variables as values, and the data type determines the kind of operations that can be carried out using these variables.

In this article we are going to focus on the string data type and we are going to talk about the methods and properties that can be applied on a string.

Properties and methods are useful tools in programming, especially when developing or working on a project that requires thousand or hundred(s) lines of codes. So, in this article you are going to learn the following:

i) What are JavaScript strings Methods and Properties

ii) Examples of properties and methods in JavaScript strings

iii) Conclusion

What are JavaScript Strings Methods and Properties

In JavaScript primitive data types such as strings are allowed to have properties and methods. This is because when executing methods or properties on strings, they are treated as objects.

Properties in JavaScript helps developers to get certain types of information from a set of objects (in this case strings). For example, say you want to check the length or type of data we make use of properties.

Methods in JavaScript are used by developers to carry out an operation on a string. For example, cutting strings in to parts, changing letters of a string and so on. Now there are numerous types of methods and properties to pick from but for the cause of this article we are only going to look at a few of the most important ones in the next section.

String properties and methods in JavaScript

In JavaScript primitive data types are provided with methods and properties, this makes it possible for you to check the length, to replace string characters with new ones or to slice strings. These methods and properties are numerous, but I will try as much as I can to show you most of the important methods and how to apply them in JavaScript.

Properties of strings in JavaScript always follow this syntax. Say you have a variable called “name” and you want to check the length of the string inside the variable, you make use the following syntax:

let name = "Precious"

console.log(name.length)

From the example above, you will notice the use of period(.) and the property name after the variable name, that is how to use properties in JavaScript.

While for methods we add a pair of parenthesis to the methods name, so performing an action using method will look like this:

let name = "Precious"

console.log(name.indexOf("P"))

So, with this in mind let’s take a look at some important string properties and methods.

1) Length:

Just as you saw from the previous example to check the length of a string, we make use of the length property. The length property always returns a result that is one more than the index of the string.

That is from our example the .length property will produce 8, while the index of the last character will be 7 (when we perform the .indexOf( ) method on the name variable). This is because in JavaScripting indexing of characters begins from 0, so the last character in our case will have an index of 7 while the length of the string will be 8.

2) The slice( ) Method:

The slice( ) method in JavaScript is used for extraction of strings part. The extracted parts of the string is returned as a new string.

This method takes two parameters, the first parameter denotes the starting point from which the slicing will begin and the second parameter denotes where the slicing should end (up to but not including).

It is important to note that string indexing beginnings from zero (0) so, the first letter or character in a string have an index of zero (0) and the second character have an index of one (1), and also remember that whitespaces are counted as part of a string. This is important when working with the slice( ) method in order to know where to start slice from.

The following example will slice out the portion of the string beginning from position 12 to position 36 (37-1).

Example:

let str = "Sandra said, I love banana and oranges"

console.log(str.slice(12, 37))

The example above will slice out the part of the string that have and index of 12 and stop slicing when it gets to the 36th position, so this will return I love banana and oranges.

The slice( ) method can also take negative values as parameters, passing negative parameter into the slice( ) will cause it to start slicing from the end of the string (i.e numbering or indexing of strings will begin from the last letter)

Example:

let str = "Sandra said, I love banana and oranges"

console.log(str.slice(-25, -1))

The above example will slice out “I Love banana and orange”, this is because indexing from the back letter “s” now have an index of 0 and letter ‘’e” have an index of -1 and so on until it gets to letter “I” which have index of -24 and then it stops (up to but not including -25).

It is also possible to omit the last argument in the extraction. Doing this will make the slice method to slice out the remining characters that comes after the first argument.

Example:

let str = "Sandra said, I love banana and oranges"

console.log(str.slice(12))

The above example will slice out “I love banana and oranges”.

The slice( ) method is not the only method that you can use in extracting strings. You can also use the substring ( ) and substr( ) methods.

3) Substring ( ) method:

The substring( ) operates similarly to the slice( ) method. It accepts two arguments that indicates the starting and ending points for slicing, but the only difference between the substring( ) and slice( ) method is that, the substring( ) method does not accepts negative argument but every other rule applies to it.

Example:

let str = "Sandra said, I love banana and oranges"

console.log(str.substring(12, 38))

From the example above the substring( ) method will extract the strings “I love banana and oranges”.

So you can also decide to omit the second parameter if you want to just cut through the entire string and still get a perfect result.

Example:

let str = "Sandra said, I love banana and oranges"

console.log(str.substring(12))

4) Substr( ) method:

The substr( ) method takes two parameters, but unlike the slice( ) method and the substring( ) where the first and second parameter represents start and stop respectively, the second parameter in a substr( ) method represents how long an extraction should be, while the first parameter represents the starting point for the extraction.

Example:

let str = "Sandra said, I love banana and oranges"

console.log(str.substr(12, 14))

From the above example, the substr( ) method will count to index number 12 (I) and starts to extract any letter that comes after I until it gets to the 13th letter after I (14-1).

Put it this way, after the position for the extraction start point is reached, the substr( ) method gives the next character that comes after it an index of 0. So knowing this we start counting from the character after “I” giving them index numbers of 0, 1, 2 and so on until we get to 14. So the result for this operation will be “I love banana and oranges”.

Well, we have seen how we can extract parts of a string using JavaScript methods. But extraction of parts is not the only thing we can do with strings there are other things like replacing characters in strings, turning lower case characters to uppercase and uppercase to lower case. All these have their different methods and we will talk about them shortly.

5) replace( ) method:

Sometimes while programming we might want to give items in variables new values.

For example, let’s say we have a string that says: “I LOVE MICROSOFT”. Maybe sometime in the future we might want to change that “Microsoft” into something else let’s say “HASHHODE”. Well it’s a tradition sometimes to reassign a new string to that variable, and put “HASHNODE” instead of “MICROSOFT”.

That could be helpful, but it is an old fashion way of doing things, we can actually achieve our goal with the replace( ) method.

The replace method is used on JavaScript strings when we want to replace a specified value in the string with another value. For example, from our previous examples if we want to change the word “MICROSOFT” to something like “HASHNODE”, we can do so using the replace( ) method.

An important point to note is that the replace method is case sensitive, so doing something like this:

let str = “I love MICROSOFT”

let newStr = str.replace(“Microsoft”, “Hashnode”)

console.log(newStr)

will produce an error.

Because the letter “MICROSOFT” and “Microsoft” are not the same thing.

But if you should do something like this:

let str = “I love MICROSOFT”

let newStr = str.replace(“MICROSOFT”,“Hashnode”)

console.log(newStr)

It will run perfectly well changing the Microsoft in the first variable to “hashnode”. So, you should see something like this:

“I love hashnode”.

But in case you might want to use the replace( ) without bordering about case sensitivity you can make use of the regular expression /i. Note that regular expression in JavaScript are written without quotes.

Example:

let str = “I love MICROSOFT”

let newStr = str.replace(/Microsoft/i, “Hashnode”)

console.log(newStr)

with the help of the regular expression /i the word “MICROSOFT” will be replaced by “Hashnode”, even though the case of the first and second “Microsoft” does not match.

Also note that by default the replace( ) method tends to replace only the first match of each specified word. For example if we had more than one “MICROSOFT” in the sentence above, the replace statement will only work on the first match it sees leaving the other ones to remain the same.

Example:

let str = "I love MICROSOFT and I am a fan of Microsoft"

let newStr = str.replace(/Microsoft/i ,"Hashnode")

console.log(newStr)

From the example above only the first “Microsoft” will be converted to “Hashnode”, the other one will remain the same. In order to change all instances of “Microsoft” in the string, make use of the regular expression /g to match the string globally. Don’t worry about regular expressions for now, they are not so important in understanding the content of this article.

Example:

let str = "I love Microsoft and I am a fan of Microsoft"

let newStr = str.replace(/Microsoft/g ,"Hashnode")

console.log(newStr)

Running the code above will match all instances of “Microsoft” in the string and change them to

“Hashnode” and this will produce a result like this:

“I love hashnode and I am a fan of hashnode”

6) toUpperCase( ) and toLowerCase( ) methods:

Conversion of strings from lowercase letters to uppercase letters is also possible in JavaScript.

To convert a string from lowercase to uppercase make use of toUpperCase( ) method in this format:

Example:

let str = "I love Microsoft and I am a fan of Microsoft"

let newStr = str.toUpperCase()

console.log(newStr)

Running the example above will produce a result that changes all characters in the variable “str” to uppercase. So instead having an output of lowercase letters, you will get an output of all uppercase letters.

Similarly if you have a text of uppercase letter you can convert it to lower case by using the toLowerCase( ) method. So from the previous example if want to convert the text in the “newStr” variable to lowercase letters, we can do so like this.

Example:

let str = "I love Microsoft and I am a fan of Microsoft"

let newStr = str.toUpperCase()

let lowerCase = newStr.toLowerCase() 

console.log(lowerCase)

Ok in order not to confuse you let me do something else apart from the first example

Example2:

let text = "MICROSOFT"

let newtext = text.toLowerCase();

console.log(newtext)

The example above will print out the text “MICROSOFT” in smaller or lowercase letters.

You can also find and check for positions of characters in a string. This is also called searching for strings. The methods applied for this are:

7) string.indexOf( ):

In order to properly extract part of a string you need to know the position (index) of each character in the string. You can do this by manually numbering each character, giving the first letter an index of 0 or by automatically getting the position of the characters you want to use.

The first method is a rather tedious procedure as you may want to save more time and this is where the second method comes in.

The indexOf( ) method is used in JavaScript for searching the position of characters in a string. Knowing the position (index) of characters in a string can help you in extraction of parts.

Example:

let str = "I love Microsoft and I am a fan of Microsoft" 

console.log(str.indexOf("Microsoft"))

Note that the indexOf( ) method will return the position of the first occurrence of a specified text. So from our example above, even though we have two occurrences of “Microsoft” it will only give the position of the first “Microsoft” (which is 7).

So, now with this information, you can perform extraction on the string

Example:

let str = "I love Microsoft and I am a fan of Microsoft" 

console.log(str.indexOf("Microsoft"))

console.log(str.slice(7))

8) String.lastIndexOf( ):

The lastIndexof( ) method is also a method for searching through strings but unlike the indexOf( ) method where the first occurrence of the specified text is returned, the lastIndexOf( ) returns the last occurrence of the text.

So, in a case where you have multiple occurrence of a character in a string using the lastIndexOf ( ) will give you the position of the last occurrence of the character

Example:

let str = "I love Microsoft and I am a fan of Microsoft" 

console.log(str.lastIndexOf("Microsoft"))

console.log(str.slice(7))

It is also possible to perform bolean operations on strings. That is, we can perform operations that returns true if a certain statement is true or false if it is not true.

Example of such methods are:

9) Includes( ) :

To check if a certain string contains a specified value, make use of the includes( ) method.

The includes( ) method returns true if the specified value is contained in the string for example in the case above you can check if we have the word “fan” in the string like this:

let str = "I love Microsoft and I am a fan of Microsoft" 

console.log(str.includes(“fan”))

This will return true because, obviously we have the word “fan” in the string.

The includes() method is not supported in internet Explorer, but it is supported by all other browsers, like chrome, Firefox, Edge, safari and Opera.

You can also include a position where you want the search to begin from by including a start index number, but this is quit optional, because in the absence of the start index number, a default index of Zero (0) is passed as a starting point, this implies that the search will beginning from the first character In the string.

But in a case like the example above where we have two instances of a word “Microsoft” if for instance you want to check for the second “Microsoft” you have to include a start index that comes after the first Microsoft like this:

let str = "I love Microsoft and I am a fan of Microsoft" 

console.log(str.includes(“Microsoft”,16)

This will return true because after the first Microsoft there is another occurrence of Microsoft.

10) String.startsWith( ):

Another method that returns a bolean value in JavaScript is the startsWith( ) method.

Unlike the includes( ) method where we get to search for a particular value in a string we use the startsWith( ) method to know if a string begins with a specified value.

For example, you can check if the string in the previous example begins with “I” ( which obviously it does)

Example:

let str = "I love Microsoft and I am a fan of Microsoft" 

console.log(str.startsWith("I"))

From the example, we are going to have true returned to us because obviously our sting begins with “I”.

For clarity sake let’s check for something else. Let’s say a word in the string, like “Microsoft” and let’s see what we get.

let str = "I love Microsoft and I am a fan of Microsoft" 

console.log(str.startsWith("Microsoft"))

From the above example, you will get a false as a return value, this is because the string does not start with the word “Microsoft”.

You can also specify a position where you want to start searching from using a start index.

Let’s say we want to check if after the 7 position the next value of the string is Microsoft all we have to do is to use the startsWith( ) and include 7 as a start index.

Example:

let str = "I love Microsoft and I am a fan of Microsoft" 

console.log(str.startsWith("Microsoft", 7))

This will return true, because after the 7th position in the string we have the word Microsoft.

11) String.endsWith() :

Lastly we have the endsWith( ) method which is a direct opposite of the startwith( ) method in terms of what they do.

The endsWith( ) returns true if the last value of a string matches a specified value unlike the startsWith( ) that matches the first value.

So from the previous example that we had, an endsWith( ) method will return true if (obviously it does) the values in the string ends with Microsoft.

Example:

let str = "I love Microsoft and I am a fan of Microsoft" 

console.log(str.endsWith("Microsoft", 7))

The endsWith( ) method also accepts two parameters just like the other two examples listed above.

The first parameter, will be the specified string that would be searched for and the second parameter which is optional will be the length to search

Example:

let str = "I love Microsoft and I am a fan of Microsoft" 

console.log(str.endsWith("Microsoft", 16))

This will return true because index 0 to index 15 (16-1) ends with the specified value Microsoft.

Note that all of the three methods mentioned above are case sensitive. So, using all lowercase or all uppercase letters in any of the example will give an error.

Conclusion

So that is all for strings methods and properties in JavaScript and I would love to say a very big thank you to you for following up to this point.

Well it quite important to note that these methods and properties are not the only methods that works on strings in JavaScript, there are other ones, but these ones will be pretty much handy and helpful to you in making your programming life much easier.

The use of strings in JavaScript Is something that comes often and knowing what to do when handling strings can be very helpful in making our work beautiful and less stressful. In this article you saw some of the methods that could be applied when working with strings.

You saw how to use the indexOf() methods and why it is important and also you saw the use of lastIndexOf () method. I also talked about the use of the length property and how it is different from the indexOf property.

It was quite an adventure and I will love to see comments and may be corrections from you if you have one thank you and God bless you.