JavaScript string methods

web
mobile

String Methods and Properties

Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.


String Length

The length property returns the length of a string:


                      var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                      var sln = txt.length;  // Result 26
                

Finding a String in a String

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:


                      var str = "Please locate where 'locate' occurs!";
                      var pos = str.indexOf("locate");  // Result 7
                  

Note: JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third etc.

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:


                      var str = "Please locate where 'locate' occurs!";
                      var pos = str.lastIndexOf("locate");  // Result 21
                    

Both indexOf(), and lastIndexOf() return -1 if the text is not found.


                      var str = "Please locate where 'locate' occurs!";
                      var pos = str.lastIndexOf("John");   // Result -1
                  

Both methods accept a second parameter as the starting position for the search:


                      var str = "Please locate where 'locate' occurs!";
                      var pos = str.indexOf("locate",15);  // Result 21, because it will skip the first "locate" string to start searching from the position 15
                    

Searching for a String in a String

The search() method searches a string for a specified value and returns the position of the match:


                      var str = "Please locate where 'locate' occurs!";
                      var pos = str.search("locate");   // Result 7
                  

Did You Notice?

The two methods, indexOf() and search(), are equal?

They accept the same arguments (parameters), and return the same value?

The two methods are NOT equal. These are the differences:

  • The search() method cannot take a second start position argument.
  • The indexOf() method cannot take powerful search values (regular expressions).

You will learn more about regular expressions in a later chapter.


Extracting String Parts

There are 3 methods for extracting a part of a string:

  • slice(start, end)
  • substring(start, end)
  • substr(start, length)

The slice() Method

slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: the start position, and the end position (end not included).

This example slices out a portion of a string from position 7 to position 13 :


                    <p id="example-1"></p>
      
                    <script>
                        var str = "Apple, Banana, Kiwi";
                        var res = str.slice(7, 13);
                        document.getElementById("example-1").innerHTML = res;  // Result "Banana"
                    </script>
                
                  

Live preview

Remember: JavaScript counts positions from zero. First position is 0.

If a parameter is negative, the position is counted from the end of the string.

This example slices out a portion of a string from position -19 to position -14:


                    <p id="example-2"></p>
      
                    <script>
                        var str = "Apple, Banana, Kiwi";
                        var res = str.slice(-19, -14);
                        document.getElementById("example-2").innerHTML = res;
                    </script>
                  

Live preview

If you omit the second parameter, the method will slice out the rest of the string:


                    var res = str.slice(7);  // Result "Banana, Kiwi"
                

or, counting from the end:


                  var res = str.slice(-12);  // Result "Banana, Kiwi"
                

The substring() Method

substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.


                    var str = "Apple, Banana, Kiwi";
                    var res = str.substring(7, 13);  // Result "Banana"
                  

If you omit the second parameter, substring() will slice out the rest of the string.


The substr() Method

substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.


                    <p id="example-3"></p>
      
                    <script>
                        var str = "Apple, Banana, Kiwi";
                        var res = str.substr(2, 15);
                        document.getElementById("example-3").innerHTML = res;  // Result "ple, Banana, Ki"
                    </script>
                  

Live preview

If you omit the second parameter, substr() will slice out the rest of the string.


                    var str = "Apple, Banana, Kiwi";
                    var res = str.substr(7);  // Result "Banana, Kiwi"
                  

If the first parameter is negative, the position counts from the end of the string.


                    var str = "Apple, Banana, Kiwi";
                    var res = str.substr(-4);  // Result "Kiwi"
                

Replacing String Content

The replace() method replaces a specified value with another value in a string:


                      <button id="button-ex-4">Try it</button>
      
                      <p id="example-4">Please visit Microsoft!</p>
                  
                      <script>
                        var str = document.getElementById("example-4").innerHTML;
                        var txt = str.replace("Microsoft", "MDBootstrap");

                        document.getElementById("button-ex-4").onclick = function () {
                            document.getElementById("example-4").innerHTML = txt;
                        };
                    </script>
                  

Live preview

Please visit Microsoft!

Note: The replace() method does not change the string it is called on. It returns a new string.

By default, the replace() function replaces only the first match:


                      str = "Please visit Microsoft and Microsoft!";
                      var n = str.replace("Microsoft", "MDBootstrap");  // Result "Please visit MDBootstrap and Microsoft!"
                

By default, the replace() function is case sensitive. Writing MICROSOFT (with upper-case) will not work:


                      str = "Please visit Microsoft!";
                      var n = str.replace("MICROSOFT", "MDBootstrap");  // It won't work
                  

Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():


                      <button id="button-ex-5">Try it</button>
      
                      <p id="example-5">Hello World</p>
                  
                      <script>
                        var str = document.getElementById("example-5").innerHTML;

                        document.getElementById("button-ex-5").onclick = function () {
                            document.getElementById("example-5").innerHTML = str.toUpperCase();
                        };
                    </script>
                  

Live preview

Hello World

A string is converted to lower case with toLowerCase():


                      var text1 = "Hello World!";       // String
                      var text2 = text1.toLowerCase();  // text2 is text1 converted to lower
                

The concat() Method

concat() joins two or more strings:


                      <p id="example-6"></p>
      
                      <script>
                        var text1 = "Hello";
                        var text2 = "World!";
                        var text3 = text1.concat(" ", text2);
                        document.getElementById("example-6").innerHTML = text3;
                    </script>
                

Live preview

The concat() method can be used instead of the plus operator. These two lines do the same:


                      var text = "Hello" + " " + "World!";
                      var text = "Hello".concat(" ", "World!");
                  

Note: All string methods return a new string. They don't modify the original string. Formally said: Strings are immutable: Strings cannot be changed, only replaced.


String.trim()

The trim() method removes whitespace from both sides of a string:


                      var str = "       Hello World!        ";
                      alert(str.trim());   // Result  "Hello Worlds"
                

Exercises - test your knowledge

Exercise 1

Use the slice method to return the word "bananas".


                      var txt = "I can eat bananas all day";
                      var x = 
                

                        var txt = "I can eat bananas all day";
                        var x = txt.slice (10,17);
                    

Exercise 2

Use the correct String method to replace the word "Hello" with the word "Welcome".


                      var txt = "Hello World";
                      var x = 
                

                        var txt = "Hello World";
                        var x = txt.replace ("Hello", "Welcome");
                    

Exercise 3

Convert the value of txt to upper case.


                      var txt = "Hello World";
                

                        var txt = "Hello World";
                        var x = txt.toUpperCase();
                

Exercise 4

Convert the value of txt to lower case.


                        var txt = "Hello World";
                  

                      var txt = "Hello World";
                      var x = txt.toLowerCase();
              

Exercise 5

Use the concat() method create a string that says "Hello World!".


                      var str1 = "Hello ";
                      var str2 = "World!";
                      var result = 
                

                        var str1 = "Hello ";
                        var str2 = "World!";
                        var result = str1.concat(str2);
                    

Rate this lesson

Previous lesson Next lesson

Spread the word:
Do you need help? Use our support forum

About the author

User avatar
Michal Szymanski
Co-Founder at MDBootstrap & BrandFlow. Entrepreneur, web developer, UI/UX designer, marketing analyst. Dancer and nerd in one.