Basics of JavaScript: Part 5 (String Functions)

Introduction

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

Adding Strings in JavaScript

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

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

Concatenating Strings in JavaScript

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

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

Open the file in a browser.

	
Basics of JavaScript: Part 5 (String Functions)

Click OK.

	
Basics of JavaScript: Part 5 (String Functions)

Note

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

Adding a single quote or double quote in JavaScript

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

var myFirstVar = 'Hello and welcome to C-Sharpcorner.com';    
var mySecondVar = "Hello and welcome to Basics of JavaScript Tutorials";   

When the user requests this page, we want to display the preceding strings in an alert box window. But we want the C-Sharpcorner.com part wrapped between double quotes and JavaScript between single quotes.

/* Adding single or double quote inside a string */    
var myFirstVar = 'Hello and welcome to "C-Sharpcorner.com"';    
var mySecondVar = "Hello and welcome to Basics of 'JavaScript' Tutorials";    
    
alert(myFirstVar);    
alert(mySecondVar);   

Open the file in a browser.

	
Basics of JavaScript: Part 5 (String Functions)

Click OK.

	
Basics of JavaScript: Part 5 (String Functions)

So, we got the expected result.

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

/* adding single or double quote inside a string */    
var myFirstVar = 'Hello and welcome to \'C-Sharpcorner.com\'';    
var mySecondVar = "Hello and welcome to Basics of \"JavaScript\" Tutorials";    
alert(myFirstVar);    
alert(mySecondVar);   

	
Basics of JavaScript: Part 5 (String Functions)

	
Basics of JavaScript: Part 5 (String Functions)

Note

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.

UpperCase in JavaScript 

Use the uppercase function to convert the lowercase string into uppercase in JavaScript.

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

Output

	
Basics of JavaScript: Part 5 (String Functions)

LowerCase in JavaScript

Use the lowercase function to convert an uppercase string into lowercase in JavaScript.

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

Output

	
Basics of JavaScript: Part 5 (String Functions)

Length Property in JavaScript

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

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

Output

	
Basics of JavaScript: Part 5 (String Functions)

The output includes white space.

Trim function  in JavaScript

We can use the trim function in JavaScript to remove whitespace from two or more strings.

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

Output

	
Basics of JavaScript: Part 5 (String Functions)

Replace function  in JavaScript

Use the replace function in JavaScript to replace part of a string with a specified value.

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

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

Output

	
Basics of JavaScript: Part 5 (String Functions)

Advantages of Global Case-Insensitive  in JavaScript

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.

	
Basics of JavaScript: Part 5 (String Functions)

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

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

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

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

Output

	
Basics of JavaScript: Part 5 (String Functions)

Substring function  in JavaScript

The Substring function in JavaScript 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.

Suppose the value of the start parameter is greater than the end parameter. In that case, 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

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

Output

	
Basics of JavaScript: Part 5 (String Functions)

Example 2

In this example, we will leave the end position blank.

<script>    
   var myVar = "Hello World";    
   var output = myVar.substring(6);    
   alert(output);    
</script>   

Output

	
Basics of JavaScript: Part 5 (String Functions)

Example 3

In this example, we will specify a more excellent value for the start parameter and a smaller value for the end parameter.

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

Output

	
Basics of JavaScript: Part 5 (String Functions)

A real-time example of a substring function

In this demo, we will see how to slice an email address's user name and domain name and display them in their respective TextBox.

Step 1

Create a form like this,

	
Basics of JavaScript: Part 5 (String Functions)

<html>    
    <head>    
        <title></title>    
    </head>    
    <body>    
        <form>    
            <table border="1" style="border-collapse:collapse">    
                <tr>    
                    <td>Email Address</td>    
                    <td>    
                        <input type="text" id="webName"></input>    
                    </td>    
                </tr>    
                <tr>    
                    <td>User Name</td>    
                    <td>    
                        <input type="text" id="UserName"></input>    
                    </td>    
                </tr>    
                <tr>    
                    <td>Domain Name</td>    
                    <td>    
                        <input type="text" id="DomainName"></input>    
                    </td>    
                </tr>    
                <tr>    
                    <td colspan="2">    
                        <input type="button" id="btnGetDetails" value="Click" onclick="myfunction()">    
                        </td>    
                    </tr>    
                </table>    
            </form>    
            <script>    
function myfunction(){    
    
}    
</script>    
        </body>    
    </html>   

Step 2

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

< script > function myfunction() {    
    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    
    //after we got the email address, now we need to slice them in two parts    
    
    //part 1 - User Name    
    var userName = myEmail.substring(0, myEmail.indexOf('@'));    
    //once we get the user name, the next step is to assign the user name as a value for the UserName textbox.    
    document.getElementById('UserName').value = userName;    
    
    //part 2 - Domain Name    
    var domainName = myEmail.substring(myEmail.indexOf('@') + 1);    
    document.getElementById('DomainName').value = domainName;    
} < /script>   

Note

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

Output

	
Basics of JavaScript: Part 5 (String Functions)

Summary

This article taught us how to add and concat strings in JavaScript. We have also discussed some useful string functions and seen the advantages of using Global Case-Insensitive in JavaScript.

I hope you like it. Thank you.


Similar Articles