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:
- Adding Strings
- Concatenating Strings
- Adding single or double quotes inside a string
- Convert string to uppercase
- Convert string to lowercase
- Length property in JavaScript
- Trim function
- Replace function
- Advantage of using Global Case-Insensitive
- Substring function
- A real time example of substring function
Adding Strings
In JavaScript, anything wrapped inside single or double quotes is considered to be a string.
- <script type="text/javascript">
- var singleQuoteString = 'This is a string';
- var doubleQuoteString = "This is also a stirng";
- </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.
-
- 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.
Click OK.
Note:
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.
- var myFirstVar = 'Hello and welcome to C-Sharpcorner.com';
- 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 C-Sharpcorner.com part to be wrapped between double quotes and JavaScript between single quotes.
-
- 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.
Click OK.
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.
-
- var myFirstVar = 'Hello and welcome to \'C-Sharpcorner.com\'';
- var mySecondVar = "Hello and welcome to Basics of \"JavaScript\" Tutorials";
- alert(myFirstVar);
- alert(mySecondVar);
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
To convert the lowercase string into uppercase, use the uppercase function.
-
- var ConverToUpperCase = 'this is an uppercase string';
- alert(ConverToUpperCase.toUpperCase());
Output
LowerCase
To convert an uppercase string into lowercase, use the lowercase function.
-
- var ConverToLowerCase = 'THIS IS A LOWERCASE STRING';
- alert(ConverToLowerCase.toLowerCase());
Output
Length Property
To get the total size of a string, use the length property.
-
- var VarLength = 'Hello World';
- alert(VarLength.length);
Output
The output includes the white space.
Trim function
To remove whitespace from two or more strings, we can use the trim function.
-
- var beforeTrim = " Hello ";
- var beforeTrimTwo = "JS"
- var afterTrim = beforeTrim.trim()+beforeTrimTwo.trim();
- alert(afterTrim);
Output
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.
-
- var myVar = "Welcome to JvScript Tutorials";
- var ReplaceMyVar = myVar.replace("JvScript","JavaScript");
- alert(ReplaceMyVar);
Output
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).
- 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.
Output
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
- <script>
- var myVar = "Hello World";
- var output = myVar.substring(6,11);
- alert(output);
- </script>
Output
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
Example 3
In this example we will specify a greater value for the start parameter and a smaller value in the end parameter.
- <script>
- var myVar = "Hello World";
- var output = myVar.substring(7,0);
- alert(output);
- </script>
Output
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:
- <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;
-
-
-
- var userName = myEmail.substring(0, myEmail.indexOf('@'));
-
- document.getElementById('UserName').value = userName;
-
-
-
- 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
Summary
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.