Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get substring of a string in jQuery?
To get substring of a string in jQuery, use the substring() method. It has the following two parameters:
- from ? The from parameter specifies the index where to start the substring.
- to ? The to parameter is optional. It specifies the index where to stop the extraction. When nothing is mentioned, it extracts the remaining string from the start index to the end.
Syntax
The syntax for the substring() method is ?
string.substring(from, to)
Example
You can try to run the following code to learn how to get substring of a string in jQuery ?
<!DOCTYPE html>
<html>
<head>
<title>jQuery substring</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
var str1 = "Hello World!";
var subStr = str1.substring(0, 5);
$("#result").text("Substring: " + subStr);
});
$("#button2").click(function(){
var str2 = "jQuery Substring Example";
var subStr2 = str2.substring(7); // Extract from index 7 to end
$("#result").text("Substring: " + subStr2);
});
});
</script>
</head>
<body>
<p>Original String: "Hello World!"</p>
<button id="button1">Get substring (0, 5)</button>
<button id="button2">Get substring from index 7</button>
<p id="result"></p>
</body>
</html>
The output will display ?
When clicking first button: Substring: Hello When clicking second button: Substring: Substring Example
Conclusion
The substring() method is a JavaScript string method that works seamlessly within jQuery applications to extract portions of strings based on specified start and end positions.
Advertisements
