Welcome to the Javascript String Methods Homepage, Guest!


Javascript | To help with Strings




String Methods

This tutorial will focus on some of the most commonly used methods that accompany the use of Strings. Strings are technically primitive values, but Javascript treats all primitive values are objects while executing the methods and properties.




Length

The length property or method will return the length of a string primitive or object:

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p> <br>
        <p id="tutorial1"></p> <br>
        <p id="tutorial2"></p> <br>

        <script>
            var txt = "txt";
            var txt1 = "James Patterson";
            var txt2 = "abcdefghijklmnopqrstuvwxyz";

            document.getElementById("tutorial").innerHTML = txt.length;
            document.getElementById("tutorial1").innerHTML = txt1.length;
            document.getElementById("tutorial2").innerHTML = txt2.length;
        </script>

    </body>
</html>



Output: 3 15 26

The values are broken down into individual characters, counted, and a number value is returned to the user. The number value will be how many individual characters are located within the String object. If we add a blank space to the end of each string in the example above, the numbers returned will be different:

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p> <br>
        <p id="tutorial1"></p> <br>
        <p id="tutorial2"></p> <br>

        <script>
            var txt = "txt ";
            var txt1 = "James Patterson ";
            var txt2 = "abcdefghijklmnopqrstuvwxyz ";

            document.getElementById("tutorial").innerHTML = txt.length;
            document.getElementById("tutorial1").innerHTML = txt1.length;
            document.getElementById("tutorial2").innerHTML = txt2.length;
        </script>

    </body>
</html>



Output: 4 16 27




Finding Strings inside of Strings

indexOf()

Sometimes you might need to find individual parts of a String. Perhaps a string is created using user information entered into a web form, and the information is concatenated together. So, we might have a string with a firstName, lastName, and email address. We might want to find only the email address or the lastName. The indexOf method will return the index of the first occurrence of the text you specify.

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p><br>
        <p id="tutorial2"></p>

        <script>
            var strValue = "First: James, Last: Patterson, Email: blah@blah.com";
            var positionOfString = strValue.indexOf("Email") + 7;
            document.getElementById("tutorial").innerHTML = positionOfString;
            var positionOfString2 = strValue.indexOf("blah@blah.com");
            document.getElementById("tutorial2").innerHTML = positionOfString2;
        </script>

    </body>
</html>



Output: 38 38

The above text shows how we can locate certain parts of a string if we know what part of it is. There are ways to find things within a string using regex and so forth, but those are for later tutorials. The code above will find the Email portion of the string created, and add the value of 7 to the number returned. The number that is then returned should be the index position of the email address we are trying to locate. The two numbers returned are 38, and therefor what we are looking for in terms of finding our specific part of the string.

lastIndexOf()

If you have a string with the same text you are looking for in more than one location, lastIndexOf is your guy:

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p><br>
        <p id="tutorial2"></p>

        <script>
            var strValue = "First: James, Last: Patterson, Email: blah@blah.com";
            var positionOfString = strValue.lastIndexOf("blah")
            document.getElementById("tutorial").innerHTML = positionOfString;
        </script>

    </body>
</html>



Output: 43

The methods indexOf and lastIndexOf will return a value of -1 if the text being searched for is unable to be found. Javascript also counts from 0, 1, 2, 3...n, and will finish counting when it reaches the end; n.

The methods indexOf and lastIndexOf will accept a second parameter. The second parameter is the starting position for the search. This just speeds up the search a bit, but you wouldn't bother searching for it if you knew where it was now would you?

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var str = "Oh say can you see, by the dawns early light";
            var pos = str.indexOf("dawns",12);

            document.getElementById("tutorial").innerHTML = pos;
        </script>

    </body>
</html>



Output: 27

search()

The method search will locate the value you wish to find inside a string, and return the position of the matching index.

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var str = "Oh say can you see, by the dawns early light";
            var pos = str.search("dawns",12);

            document.getElementById("tutorial").innerHTML = pos;
        </script>

    </body>
</html>



Output: 27

The two methods, indexOf() and search() return equal values. They will accept the same arguments or parameters, return the same values, correct? The two are the same except search() is a bit different:

  • search() cannot take a second start position argument
  • search() can take much more powerful search values, such as regular expressions




Extracting Parts of Strings

You can effectively extract parts of a string value in three individual ways using built in functions or methods:

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


slice()

This method will extract a portion of a string, and return the extracted part in a new string value. The method takes two arguments or parameters: the starting position (index), and the ending position (index). The following example will show how to cut out a portion of a string:

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var vehicles = "car, motorcycle, truck";
            var portion = vehicles.slice(5, 15);

            document.getElementById("tutorial").innerHTML =
            "What do I love to drive most, my " + portion;
        </script>

    </body>
</html>



Output: What do I love to drive most, my motorcycle

If you leave out the second parameter to the method call, the string will return the rest of the available string:

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var vehicle = "car, motorcycle, truck";
            var str = vehicle.slice(5);

            document.getElementById("tutorial").innerHTML =
            "I love to drive my " + str;
        </script>

    </body>
</html>



Output: I love to drive my motorcycle, truck

Negative parameters

If you put a negative parameter into slice, the position will start counting from the end of the string starting at 0, -1, -2..-n . Remember that negative numbers only work in IE9 and up. The example below will slice out a portion of the string between the -17 and -7 range:

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var vehicle = "car, motorcycle, truck";
            var str = vehicle.slice(-17,-7);

            document.getElementById("tutorial").innerHTML =
            "I love to drive my " + str;
        </script>

    </body>
</html>



Output: I love to drive my motorcycle

If we were to leave out the second parameter in the method call, the sliced part would show the rest of the string that is available:

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var vehicle = "car, motorcycle, truck";
            var str = vehicle.slice(-17);

            document.getElementById("tutorial").innerHTML =
            "I love to drive my " + str;
        </script>

    </body>
</html>



Output: I love to drive my motorcycle, truck

substring() method

The method substring() is very similar to the slice() method. The main difference is that substring() will not accept a negative index value at all.



<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var vehicle = "car, motorcycle, truck";
            var str = vehicle.substring(5, 15);

            document.getElementById("tutorial").innerHTML =
            "I love to drive my " + str;
        </script>

    </body>
</html>



The example above uses the substring() method to return a portion of the string we desire. Remember, if you were to leave out the second parameter in the function call, the rest of the string will be added to your result.

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var vehicle = "car, motorcycle, truck";
            var str = vehicle.substring(5);

            document.getElementById("tutorial").innerHTML =
            "I love to drive my " + str;
        </script>

    </body>
</html>



First Output: I love to drive my motorcycle

Second Output: I love to drive my motorcycle, truck

If you leave out the second parameter in substring(), the rest of the available string will be returned to you.

substr() method

The built in Javascript method substr(), is very similar to the method slice(). The main difference is the second parameter. The second parameter specifies the length of the extracted string. If the first parameter is a negative number, the position will count from the end of the string. The second parameter can not be a negative number, because the length of anything can not be negative. If you leave out the second parameter, substr() will return the rest of the string.



<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var str = "motorcycle, truck, car";
            var choice = str.substr(12, 16);

            document.getElementById("tutorial").innerHTML =
            "I love my " + choice;
        </script>

    </body>
</html>



Output: I love my truck

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var str = "motorcycle, truck, car";
            var choice = str.substr(-10);

            document.getElementById("tutorial").innerHTML =
            "I love my " + choice;
        </script>

    </body>
</html>



Output: I love my truck, car

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var str = "motorcycle, truck, car";
            var choice = str.substr(-10, -16);

            document.getElementById("tutorial").innerHTML =
            "I love my " + choice;
        </script>

    </body>
</html>



Output: I love my

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var str = "motorcycle, truck, car";
            var choice = str.substr(12);

            document.getElementById("tutorial").innerHTML =
            "I love my " + choice;
        </script>

    </body>
</html>



Output: I love my truck, car




Replacing String Content

The replace() built in method will replace a specific value with another value in the string calling the method:

<!DOCTYPE html>
<html>
    <body>

        <button onclick="myF()">Click Here</button>

        <p id="tutorial">I love to drive my car the most.</p>

        <script>
            function myF() {
                var temp = document.getElementById("tutorial").innerHTML;
                var txt = temp.replace("car","motorcycle");

                document.getElementById("tutorial").innerHTML = txt;
            }
        </script>

    </body>
</html>



The code above starts out by creating a button that has the onclick event set to myF(). The method myF() will trigger the replacement of car with motorcycle. The p element with id tutorial has a string that will be set to a variable within the Javascript code to be able to replace the characters. The variable will be named temp, temp will replace car with motorcycle, and then replace the innerHTML of the p element with id equal to tutorial. Remember, replace does not change the original string, but it does return a new string . The replace() method replaces only the first match of the string.

Output after button click: I love to drive my motorcycle the most.

<!DOCTYPE html>
<html>
    <body>

        <button onclick="myF()">Click Here</button>

        <p id="tutorial">Do I want to drive my car, car, or truck?</p>

        <script>
            function myF() {
                var temp = document.getElementById("tutorial").innerHTML;
                var txt = temp.replace("car","motorcycle");

                document.getElementById("tutorial").innerHTML = txt;
            }
        </script>

    </body>
</html>



Output: Do I want to drive my motorcycle, car, or truck?

Regular Expressions

To replace all matches, you will need to use a regular expression with the /g flag, which is global match.

<!DOCTYPE html>
<html>
    <body>

        <button onclick="myFunction()">Try it</button>

        <p id="tutorial">Do I want to drive my car, car, or truck?</p>

        <script>
            function myFunction() {
                var str = document.getElementById("tutorial").innerHTML;
                var result = str.replace(/car/g,"motorcycle");

                document.getElementById("tutorial").innerHTML = result;
            }
        </script>

    </body>
</html>



Output after button click: Do I want to drive my motorcycle, motorcycle, or truck?

Case sensitivity

By default, the replace method is case sensitive. Writing CAR instead of car will result in a failure:

<!DOCTYPE html>
<html>
    <body>

        <button onclick="myFunction()">Try it</button>

        <p id="tutorial">Do I want to drive my car, car, or truck?</p>

        <script>
            function myFunction() {
                var str = document.getElementById("tutorial").innerHTML;
                var result = str.replace(/CAR/g,"motorcycle");

                document.getElementById("tutorial").innerHTML = result;
            }
        </script>

    </body>
</html>



Output after button click: Do I want to drive my car, car, or truck?

To not worry about case at all use a regular expression coupled with a /i flag:

<!DOCTYPE html>
<html>
    <body>

        <button onclick="myFunction()">Try it</button>

        <p id="tutorial">Do I want to drive my car, car, or truck?</p>

        <script>
            function myFunction() {
                var str = document.getElementById("tutorial").innerHTML;
                var txt = str.replace(/CAR/i,"motorcycle");

                document.getElementById("tutorial").innerHTML = txt;
            }
        </script>

    </body>
</html>



Output: Do I want to drive my motorcycle, car, or truck?

We will discuss regular expressions in further detail later on.




Conversion between Upper and Lower case

A string can be converted to Upper case or Lower case at will. The built in Javascript method toUpperCase() will take a string, and convert that string into a upper case string. The built in Javascript method toLowerCase() will convert a string of characters into a lower case representation of the string.

<!DOCTYPE html>
<html>
    <body>

        <button onclick="myFunction()">Click Here</button>

        <p id="tutorial">Hello World</p>

        <script>
            function myFunction() {
                var temp = document.getElementById("tutorial").innerHTML;
                document.getElementById("tutorial").innerHTML = temp.toUpperCase();
            }
        </script>

    </body>
</html>



Output: HELLO WORLD

<!DOCTYPE html>
<html>
    <body>

        <button onclick="myFunction()">Click Here</button>

        <p id="tutorial">HELLO WORLD</p>

        <script>
            function myFunction() {
                var temp = document.getElementById("tutorial").innerHTML;
                document.getElementById("tutorial").innerHTML = temp.toLowerCase();
            }
        </script>

    </body>
</html>



Output: hello world




The concat() method

This method is quite useful when using a lot of string variables, and when you need to add blank space without having to hard code a variable just for it.

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var first = "Hello";
            var second = "World";
            var together = first.concat(" ",second);

            document.getElementById("tutorial").innerHTML = together;
        </script>

    </body>
</html>



Output: Hello World

The concat() method can be used instead of the + operator; they do achieve the same goal. All string methods do return a new string instead of modifying the original string. Strings are immutable, which means that strings cannot be changed, but they can be replaced.




Extraction of Strings

According to Javascript, there are exactly two safe ways to extract a string of characters from a string object: charAt(positionOfString) or charCodeAt(positionOfString).

charAt()

This method will return the character at a specific index or position in a string:

<!DOCTYPE html>
<html>
    <body>
    
        <p id="tutorial"></p>
        
        <script>
            var phrase = "Hello World";
            document.getElementById("tutorial").innerHTML = phrase.charAt(6);
        </script>    
            
    </body>
</html>



Output: W

charCodeAt()

This method will return the unicode of the character at the specific index in a string:

<!DOCTYPE html>
<html>
  <body>

      <p id="tutorial"></p>

      <script>
          var phrase = "HELLO WORLD";
          document.getElementById("tutorial").innerHTML = phrase.charCodeAt(0);
      </script>
  </body>
</html>



Output: 72




Converting a String to an Array

A string can be converted to an array pretty easily, and with different kinds of delimiters. If you don't add the delimiter, the returned array will contain the whole string in index[0]. If the delimiter is "", the array that is returned will be a array of single characters. The code below will break the string into an array called tempArray. The array will access the number 2 index, which is canaloupe, and return the value in the second index. You could use a comma, a blank space, or a pipe to delimit. ( ",", " ", "|")

<!DOCTYPE html>
<html>
    <body>

        <button onclick="myFunction()">Click Here</button>

        <p id="tutorial"></p>

        <script>
            function myFunction() {
                var temp = "apple, banana, canaloupe, durian, egg";
                var tempArray = temp.split(",");
                document.getElementById("tutorial").innerHTML = tempArray[2];
            }
        </script>

    </body>
</html>



Split into Characters

To split a string into individual characters, you could use the split method with the "" method:

<!DOCTYPE html>
<html>
    <body>

        <p id="tutorial"></p>

        <script>
            var phrase = "Hello World";
            var phraseArray = phrase.split("");
            var value = "";
            var i;
            
            for (i = 0; i < phraseArray.length; i++) {
                value += phraseArray[i] + " "
            }
            document.getElementById("tutorial").innerHTML = value;
        </script>

    </body>
</html>



Output: H e l l o W o r l d

The code above is unique in the way I presented it to the tutorial. I haven't used a loop in any of the tutorials so far really, but in order to display the data properly, a loop is required. First, create an empty p element with the id set to tutorial, like always, and then create the script element. Within the script tags, a phrase needs to be created with values set to Hello World. The array can be created and set to the phrase string using the split method. The value will be the proper way to display the data, but for now it needs to be set to nothing. The for loop will loop through the phraseArray array, from 0 to array's length, and print out each character with a blank space behind it. You can play with the for loop, and come up with a unique solution on your own.



Additional Information on Strings

String Properties

Property Description
constructor Returns the string's constructor function
length Returns the length of a string
prototype Allows you to add properties and methods to an object

String Methods

Method Description
charAt() Returns the character at the specified index (position)
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a new joined strings
endsWith() Checks whether a string ends with specified string/characters
fromCharCode() Converts Unicode values to characters
includes() Checks whether a string contains the specified string/characters
indexOf() Returns the position of the first found occurrence of a specified value in a string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a string
localeCompare() Compares two strings in the current locale
match() Searches a string for a match against a regular expression, and returns the matches
repeat() Returns a new string with a specified number of copies of an existing string
replace() Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced
search() Searches a string for a specified value, or regular expression, and returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
startsWith() Checks whether a string begins with specified characters
substr() Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale
toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object

All string methods return a new value. They do not change the original variable.

String HTML Wrapper Methods

The HTML wrapper methods return the string wrapped inside the appropriate HTML tag.

These are not standard methods, and may not work as expected in all browsers.

Method Description
anchor() Creates an anchor
big() Displays a string using a big font
blink() Displays a blinking string
bold() Displays a string in bold
fixed() Displays a string using a fixed-pitch font
fontcolor() Displays a string using a specified color
fontsize() Displays a string using a specified size
italics() Displays a string in italic
link() Displays a string as a hyperlink
small() Displays a string using a small font
strike() Displays a string with a strikethrough
sub() Displays a string as subscript text
sup() Displays a string as superscript text



Next, we will take a look at how Numbers play a part in Javascript.

Just follow the buttons to continue the tutorial, Guest