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,
- Adding Strings in JavaScript
- Concatenating Strings in JavaScript
- Adding single or double quotes inside a string in JavaScript
- Convert string to uppercase in JavaScript
- Convert string to lowercase in JavaScript
- Length property in JavaScript
- Trim function in JavaScript
- Replace function in JavaScript
- Advantage of using Global Case-Insensitive in JavaScript
- Substring function in JavaScript
- 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.
Click OK.
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.
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.
/* 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);
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
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
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
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
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
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.
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
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
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 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
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,
<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
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.