JavaScript

JavaScript String substring() Example

Greetings readers, in this tutorial, we will show how to use the JavaScript scripting language and the JavaScript string subString() method.

1. Introduction

JavaScript is an object-oriented programming language that allows the client-side scripting to interact with a user and deliver the dynamic pages. Most web browsers including Google Chrome, Mozilla Firefox, Safari, Internet Explorer, Microsoft Edge, Opera, etc. support it. The JavaScript scripting language includes:

  • Declaring variables
  • Maintaining the retrieving values
  • Defining and invoking functions
  • Defining classes
  • Load and use external modules
  • Define event handlers
  • And much more ….

1.1 Advantages of JavaScript Language

The pros of using the JavaScript scripting language are:

  • JavaScript is easy to learn
  • It executes on client’s browser, so eliminates the server-side processing and be executed on any OS
  • JavaScript can be used with any type of web page e.g. PHP, ASP.NET, Perl etc
  • Web-page performance increases due to client-side execution
  • JavaScript code can be minified to decrease the loading time from the server
  • Many JavaScript-based application frameworks are available in the market to create Single page web applications e.g. AngularJS, ReactJS etc.

1.2 Disadvantages of JavaScript Language

The cons of using the JavaScript scripting language are:

  • No support for networking applications
  • Does not have any multi-threading or multi-processing capabilities
  • Does not allow the file reading and writing capabilities

1.3 JavaScript subString() Method

In Javascript scripting language, the subString method returns the subset of a string object between the two specified indices. This method returns the new sub-string based on the given parameters. Over here represents the simple syntax to practice this method.

Snippet

my_string.substring(start_index, [end_index])

Where,

  • start_index is a required parameter that specifies the position from where to start the extraction. The first character is at index zero
  • end_index is an optional parameter that specifies the position up to where the extraction to end. If omitted, it extracts the rest of the string

Always remember,

  • If start_index is less than end_index, the subString method will swap the two arguments
  • Alternatively, if the start_index and the end_index is a negative number, it will be treated as zero

These new APIs make a developer life easier, really! However, it would be difficult for a beginner to understand this without an example. Therefore, let us create a simple application using the JavaScript scripting language.

2. JavaScript String substring() Example

Here is a systematic guide for implementing this tutorial using the JavaScript language.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure if you are confused about where you should create the corresponding files or folder later!

JavaScript String substring() - Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will show on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

JavaScript String substring() - Create a Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.

JavaScript String substring() - Project Details
Fig. 3: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

JavaScript String substring() - Archetype Selection
Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

JavaScript String substring() - Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId> com.javascript</groupId>
	<artifactId>JavaScriptSubstring</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

3. Application Building

Let us create an application to understand the basic building blocks of this tutorial.

3.1 Define the HTML

Let us write a simple index page in the JavaScriptSubstring/src/main/webapp/ folder. Add the following code to it:

index.jsp

<!------ JavaScript Substring Example ------>
<div class="form-group">

	<!-- start index dropdown. -->
	<label class="col-sm-2 control-label paddingTop6">Select start index: </label>
	<div class="col-sm-2">
		<select id="start_index" class="form-control">
			<option value="0">0</option>
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
			<option value="4">4</option>
			<option value="5">5</option>
			<option value="6">6</option>
		</select>
	</div>

	<!-- end index dropdown. -->
	<label class="col-sm-2 control-label paddingTop6">Select end index: </label>
	<div class="col-sm-2">
		<select id="end_index" class="form-control">
			<option value="11">11</option>
			<option value="12">12</option>
			<option value="13">13</option>
			<option value="14">14</option>
			<option value="15">15</option>
			<option value="16">16</option>
			<option value="20">20</option>
			<option value="25">25</option>
		</select>
	</div>

	<!-- button. -->
	<button type="button" class="btn btn-primary marginLeft100" onclick="getSubstring()">Substring</button>
</div>

3.2 Define the JavaScript function

Let us write a simple javascript function that takes the values from the given dropdowns and executes the subString() method on these values. Add the following code to it:

JavaScript function

function getSubstring() {
	var sindex = document.getElementById("start_index").value;
	var eindex = document.getElementById("end_index").value;

	var src_str = ("The JavaScript substring tutorial!");
	var sub_str = src_str.substring(sindex, eindex);

	document.getElementById("result").innerHTML = sub_str;
}

3.3 First application

Complete the above steps and save the file. Let us see the sample code snippet.

index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>	    
	    <title>Index Page</title>
	    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	
	    <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/3.3.7/css/bootstrap.min.css">
	
	    <script type="text/javascript">
	        function getSubstring() {
	            var sindex = document.getElementById("start_index").value;
	            var eindex = document.getElementById("end_index").value;
	
	            var src_str = ("The JavaScript substring tutorial!");
	            var sub_str = src_str.substring(sindex, eindex);
	
	            document.getElementById("result").innerHTML = sub_str;
	        }
	    </script>
	
	    <style type="text/css">
	        .paddingTop6 {
	            padding-top: 6px !important;
	        }	        
	        .marginLeft100 {
	            margin-left: 100px !important;
	        }
	    </style>
	</head>
	
	<body>
	    <div class="container">
	        <h2 align="center" class="text-primary">JavaScript Substring Example</h2>
	        <hr />
	
	        <!------ JavaScript Substring Example ------>
	        <div class="form-group">
	
	            <!-- start index dropdown. -->
	            <label class="col-sm-2 control-label paddingTop6">Select start index: </label>
	            <div class="col-sm-2">
	                <select id="start_index" class="form-control">
	                    <option value="0">0</option>
	                    <option value="1">1</option>
	                    <option value="2">2</option>
	                    <option value="3">3</option>
	                    <option value="4">4</option>
	                    <option value="5">5</option>
	                    <option value="6">6</option>
	                </select>
	            </div>
	
	            <!-- end index dropdown. -->
	            <label class="col-sm-2 control-label paddingTop6">Select end index: </label>
	            <div class="col-sm-2">
	                <select id="end_index" class="form-control">
	                    <option value="11">11</option>
	                    <option value="12">12</option>
	                    <option value="13">13</option>
	                    <option value="14">14</option>
	                    <option value="15">15</option>
	                    <option value="16">16</option>
	                    <option value="20">20</option>
	                    <option value="25">25</option>
	                </select>
	            </div>
	
	            <!-- button. -->
	            <button type="button" class="btn btn-primary marginLeft100" onclick="getSubstring()">Substring</button>
	        </div>
	        <div> </div>
	
	        <div id="demo">	        	
	            <strong>Main String: </strong><span>The JavaScript substring tutorial</span>
	            <div> </div>
	            
	            <!-- substring result. -->
	            <strong>After substring method: </strong><span id="result"></span>
	        </div>
	    </div>
	</body>
</html>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

JavaScript String substring() - Deploy Application on Tomcat
Fig. 6: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL to display the application’s index page as shown in Fig. 7.

http://localhost:8082/JavaScriptSubstring/

Server name (localhost) and port (8082) may vary as per your Tomcat configuration.

JavaScript String substring() - Index page
Fig. 7: Index page

Users can select the values from the two dropdowns and can click the button to display the sub-string of the main string as shown in Fig. 8.

JavaScript String substring() - Output
Fig. 8: Output

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

In this section, developers learned how to create a simple application with the JavaScript language. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of JavaScript String substring() for beginners.

Download
You can download the full source code of this example here: JavaScriptSubstring

Yatin

The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button