Basics of JavaScript: Part 5 (String Functions)

This is Part 5 of the Basics of JavaScript series. This article explains the various string functions available in JavaScript.

The following are the topics we have already discussed:

This article discusses the following topics:

  1. Adding Strings
  2. Concatenating Strings
  3. Adding single or double quotes inside a string
  4. Convert string to uppercase
  5. Convert string to lowercase
  6. Length property in JavaScript
  7. Trim function
  8. Replace function
  9. Advantage of using Global Case-Insensitive
  10. Substring function
  11. A real time example of substring function

Adding Strings

In JavaScript, anything wrapped inside single or double quotes is considered to be a string.

  1. <script type="text/javascript">  
  2.    var singleQuoteString = 'This is a string';  
  3.    var doubleQuoteString = "This is also a stirng";  
  4. </script> 

Concatenating Strings

The previous article of this series explained how to concatenate two strings using the “+” operator. But there is another function/method that can be used to concatenate strings, the concat() method.

  1. /*concatenating two strings using + operator and concat method*/  
  2. var myFirstVar = 'We are ';  
  3. var mySecondVar = "concatenating two string";  
  4. alert(myFirstVar + mySecondVar);  
  5. var concatResult = myFirstVar.concat(mySecondVar," using concat method");  
  6. alert(concatResult); 

Open the file in a browser.

Click OK.


We can pass multiple strings inside the concat() method each separated by commas.

Adding single quote or double quote

In the HTML document I have the following two string variables with the following string values.

  1. var myFirstVar = 'Hello and welcome to';  
  2. var mySecondVar = "Hello and welcome to Basics of JavaScript Tutorials"

Now let's say that when the user requests this page we want to display the preceding strings in an alert box window. But we want the part to be wrapped between double quotes and JavaScript between single quotes.

  1. /* Adding single or double quote inside a string */  
  2. var myFirstVar = 'Hello and welcome to ""';  
  3. var mySecondVar = "Hello and welcome to Basics of 'JavaScript' Tutorials";  
  5. alert(myFirstVar);  
  6. alert(mySecondVar); 

Open the file in a browser.

Click OK.

So, we got the expected result.

Now let's say this time we want to wrap the inside single quotes and JavaScript inside double quotes.

  1. /* adding single or double quote inside a string */  
  2. var myFirstVar = 'Hello and welcome to \'\'';  
  3. var mySecondVar = "Hello and welcome to Basics of \"JavaScript\" Tutorials";  
  4. alert(myFirstVar);  
  5. alert(mySecondVar); 

Whenever you prefer to place the entire string inside single quotes and in addition to that you want to wrap a part of a string inside single quotes then we need to wrap those additional single quotes inside a backslash that will remove the special meaning of the character.


To convert the lowercase string into uppercase, use the uppercase function.

  1. /*Uppercase function*/  
  2. var ConverToUpperCase = 'this is an uppercase string';  
  3. alert(ConverToUpperCase.toUpperCase()); 



To convert an uppercase string into lowercase, use the lowercase function.

  1. /*Lowercase function*/  
  2. var ConverToLowerCase = 'THIS IS A LOWERCASE STRING';  
  3. alert(ConverToLowerCase.toLowerCase()); 


Length Property

To get the total size of a string, use the length property.

  1. /*Length of s string */  
  2. var VarLength = 'Hello World';  
  3. alert(VarLength.length); 


The output includes the white space.

Trim function

To remove whitespace from two or more strings, we can use the trim function.

  1. /*Trim function in JavaScript*/  
  2. var beforeTrim = " Hello ";  
  3. var beforeTrimTwo = "JS"  
  4. var afterTrim = beforeTrim.trim()+beforeTrimTwo.trim();  
  5. alert(afterTrim); 


Replace function

To replace part of a string with a specified value, use the replace function.

The first parameter of this replace function expects a string that you want to replace and the second parameter is the replacement value.

  1. /*Replace function in JavaScript*/  
  2. var myVar = "Welcome to JvScript Tutorials";  
  3. var ReplaceMyVar = myVar.replace("JvScript","JavaScript");  
  4. alert(ReplaceMyVar); 


Advantages of Global Case-Insensitive

In the preceding demo we were able to replace JvScript with JavaScript.

Now what will happen if I change the JvScript to jvscript? Here everything is now in lowercase.

Let's first run and see.

In the output we got JvScript but we were expecting JavaScript.

The reason for this is, JavaScript is case-sensitive, meaning A is different from a. But if you want to make a certain part of the scripts case-insensitive then use the global case-insensitive replacement (/YourString/gi).

  1. var ReplaceMyVar = myVar.replace(/jvscript/gi,"JavaScript"); 

This /gi indicates to do global case-insensitive replacement that will treat JvScript and jvscript as the same string and will replace it with JavaScript.


Substring function

The Substring function retrieves a part of a string, in other words a substring from a string.

The substring function has two parameters, start and end. The start parameter is required and specifies the position where to start the extraction. The end parameter specifies where the extraction should end. The end positioned character is not included in the substring because the position value is a zero-based index.

If the value of the start parameter is greater than the end parameter, then the value of this substring will be swapped, meaning that the start parameter will be treated as the end parameter and the end parameter will be treated as the start parameter.

Note: This end parameter is optional.

Since the end parameter is optional, all the characters starting from the specified start position to the end of the string will be extracted.

Example 1

  1. <script>  
  2.    var myVar = "Hello World";  
  3.    var output = myVar.substring(6,11);  
  4.    alert(output);  
  5. </script> 


Example 2

In this example we will leave the end position blank.

  1. <script>  
  2.    var myVar = "Hello World";  
  3.    var output = myVar.substring(6);  
  4.    alert(output);  
  5. </script> 


Example 3

In this example we will specify a greater value for the start parameter and a smaller value in the end parameter.

  1. <script>  
  2.    var myVar = "Hello World";  
  3.    var output = myVar.substring(7,0);  
  4.    alert(output);  
  5. </script> 


Real time example of substring function

In this demo we will see how to slice the user name and a domain name of an email address and display them in their respective TextBox.

Step 1

Create a form like this:

  1. <html>  
  2.     <head>  
  3.         <title></title>  
  4.     </head>  
  5.     <body>  
  6.         <form>  
  7.             <table border="1" style="border-collapse:collapse">  
  8.                 <tr>  
  9.                     <td>Email Address</td>  
  10.                     <td>  
  11.                         <input type="text" id="webName"></input>  
  12.                     </td>  
  13.                 </tr>  
  14.                 <tr>  
  15.                     <td>User Name</td>  
  16.                     <td>  
  17.                         <input type="text" id="UserName"></input>  
  18.                     </td>  
  19.                 </tr>  
  20.                 <tr>  
  21.                     <td>Domain Name</td>  
  22.                     <td>  
  23.                         <input type="text" id="DomainName"></input>  
  24.                     </td>  
  25.                 </tr>  
  26.                 <tr>  
  27.                     <td colspan="2">  
  28.                         <input type="button" id="btnGetDetails" value="Click" onclick="myfunction()">  
  29.                         </td>  
  30.                     </tr>  
  31.                 </table>  
  32.             </form>  
  33.             <script>  
  34. function myfunction(){  
  36. }  
  37. </script>  
  38.         </body>  
  39.     </html> 

Step 2

Inside the script section, write the following in the myfunction block:

  1. < script > function myfunction() {  
  2.     var myEmail = document.getElementById('webName').value; //this line of code will fetch and store an email address from a textbox whose id is webName to myEmail  
  3.     //after we got the email address, now we need to slice them in two parts  
  5.     //part 1 - User Name  
  6.     var userName = myEmail.substring(0, myEmail.indexOf('@'));  
  7.     //once we get the user name, the next step is to assign the user name as a value for the UserName textbox.  
  8.     document.getElementById('UserName').value = userName;  
  11.     //part 2 - Domain Name  
  12.     var domainName = myEmail.substring(myEmail.indexOf('@') + 1);  
  13.     document.getElementById('DomainName').value = domainName;  
  14. } < /script> 


myEmail.substring(myEmail.indexOf('@') + 1), this +1 will exclude @ and will just display the domain name.



In this article we learned how to add and concat strings. We have also discussed some useful string functions and we have also seen the advantages of using Global Case-Insensitive.

I hope you like it. Thank you.

Up Next
    Ebook Download
    View all
    View all