How to Check a String Starts/Ends with a Specific String in jQuery?


JavaScript relationships with the HTML/CSS file, particularly with the Document Object Model (DOM), are made easier through an open-source library called "jQuery". Its traversal and manipulation of HTML files, the control of browser events, the production of DOM visuals, the facilitation of Ajax connections, and cross-platform JavaScript programming are all made easier by this package.

To verify whether a particular string constitutes a substring of another string, JavaScript provides a variety of string functions. Consequently, jQuery is dispensable to accomplish this task.

Nonetheless, we shall expound on the various approaches to verify if a string commences or terminates with another string:

  • startsWith() and endsWith() method

  • search() method

  • indexOf() method

  • substring() method

  • substr() method

  • slice() method

Suppose we have a string, str = "Hi, how are you?" and we are tasked with determining whether it begins with the startword = "Hi" and concludes with the endword = "?" .

Method 1- str.startsWith()

The str.startsWith() method in JavaScript is utilized to validate if the characters in the given string begin the designated string. This technique is case-sensitive, implying that it distinguishes between uppercase and lowercase letters.

The aforesaid approach acknowledges two parameters, as previously specified, and delineated below:

  • searchString: It constitutes a compulsory parameter that stores the string that necessitates searching.

  • start: It establishes the location in the provided string from which the searchString is to be sought. The default value is zero.

Syntax

str.startsWith( searchString , position )

Example

function func() {
		
   var str = 'Hi, how are you?';
		
   var value = str.startsWith('Hi');
   console.log(value);
}
func();

Output

true

Method 2- endsWith()

To determine if the string that is provided ends with the characters from the other string or not, use the JavaScript method str.endsWith().

The aforementioned method takes two parameters as mentioned earlier, described below:

  • searchString: It represents a string of characters that needs to be found at the end of the given string.

  • length: The length parameter determines the size of the original string from where the search string is to be examined.

When this function is executed, it returns a Boolean value of true if the searchString is found; otherwise, it returns false.

Example

function func() {
		
   var str = 'Hi, how are you?';
		
   var value = str.startsWith('you?');
   console.log(value);
}
func();

Output

false

Method 3 - string.search()

The JavaScript string.search() method is a built-in function used to search for a match between a regular expression and a specified string object.

Syntax

string.search( A )

Example

var string = "Hi, how are you?";
	
var re1 = /s/;
var re2 = /3/;
var re3 = / /;
var re4 = /, /;
	
console.log(string.search(re1));
console.log(string.search(re2));
console.log(string.search(re3));
console.log(string.search(re4));

Output

-1
-1
3
2

Method 4: String indexOf()

The str.indexOf() function in JavaScript discovers the index of the first instance of the provided string argument within the given string. The outcome is 0-based.

Syntax

str.indexOf(searchValue , index)

Example

function func() {
	
   var str = 'Hi, How are you?';
	
   var index = str.indexOf('are');
   console.log(index);
}
func();

Output

8

Method 5: String substring()

The JavaScript string.substring() method is a built-in function that returns a portion of the given string, starting from the specified start index and ending at the provided end index. The indexing in this method starts at zero (0).

Syntax

string.substring(Startindex, Endindex)

The parameters Startindex and Endindex determine the segment of the string to extract as a substring. The Endindex parameter is optional.

When the string.substring() function is executed, it creates a new string that represents a portion of the original string.

Example

var string = "Hi, how are you?";
a = string.substring(0, 4)
b = string.substring(1, 6)
c = string.substring(5)
d = string.substring(0)
	
console.log(a);
console.log(b);
console.log(c);
console.log(d);

Output

Hi, 
i, ho
ow are you?
Hi, how are you?

Method 6: String substr()

The str.substr() method in JavaScript allows you to extract a specific number of characters from the given string, starting from the specified index. This method effectively extracts a segment of the original string.

Syntax

str.substr(start , length)

Example

function func() {
	
   var str = 'Hi, how are you?';
   var sub_str = str.substr(5);
   console.log(sub_str);
}

func();

Output

ow are you?

Method 7: string.slice()

The JavaScript string.slice() method is utilized to extract a portion or slice of the provided input string and return it as a new string.

Syntax

string.slice(startingIndex, endingIndex)

Example

var A = 'Hi, How are you?';
b = A.slice(0,5);
c = A.slice(6,9);
d = A.slice(0);
	
console.log(b);
console.log(c);
console.log(d);

Output

Hi, H
w a
Hi, How are you?

Example

<!DOCTYPE html>
<html>
<head>
   <title>jQuery Methods Demo</title>
   <style>
      /* CSS Styles */
      body {
         font-family: Arial, sans-serif;
         margin: 0;
         padding: 20px;
      }

      h1 {
         text-align: center;
      }

      h2 {
         margin-top: 30px;
      }

      p {
         margin: 10px 0;
      }

      .container {
         max-width: 600px;
         margin: 0 auto;
      }

      button {
         padding: 10px 20px;
         background-color: #007bff;
         color: #fff;
         border: none;
         cursor: pointer;
         transition: background-color 0.3s;
      }

      button:hover {
         background-color: #0056b3;
      }

      input[type="text"] {
         padding: 5px;
         border: 1px solid #ccc;
         border-radius: 3px;
      }

      .output {
         font-weight: bold;
      }
   </style>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script>
      $(document).ready(function() {
         var text = "Hello, World!";
         $("#textContent").text(text);

         // startsWith() method
         $("#startsWithBtn").click(function() {
            var result = text.startsWith("Hello");
            $("#startsWithOutput").text(result);
         });

         // endsWith() method
         $("#endsWithBtn").click(function() {
            var result = text.endsWith("World!");
            $("#endsWithOutput").text(result);
         });

         // search() method
         $("#searchBtn").click(function() {
            var searchTerm = $("#searchTerm").val();
            var result = text.search(searchTerm);
            $("#searchOutput").text(result);
         });

         // indexOf() method
         $("#indexOfBtn").click(function() {
            var searchTerm = $("#indexOfTerm").val();
            var result = text.indexOf(searchTerm);
            $("#indexOfOutput").text(result);
         });

         // substring() method
         $("#substringBtn").click(function() {
            var start = $("#substringStart").val();
            var end = $("#substringEnd").val();
            var result = text.substring(start, end);
            $("#substringOutput").text(result);
         });

         // substr() method
         $("#substrBtn").click(function() {
            var start = $("#substrStart").val();
             var length = $("#substrLength").val();
            var result = text.substr(start, length);
            $("#substrOutput").text(result);
         });

         // slice() method
         $("#sliceBtn").click(function() {
            var start = $("#sliceStart").val();
            var end = $("#sliceEnd").val();
            var result = text.slice(start, end);
            $("#sliceOutput").text(result);
         });
      });
   </script>
</head>
<body>
   <div class="container">
      <h1>jQuery Methods Demo</h1>
   
      <h2>Text Content</h2>
      <p id="textContent"></p>
   
      <h2>startsWith() Method</h2>
      <button id="startsWithBtn">Check if the text starts with "Hello"</button>
      <p>Result: <span id="startsWithOutput" class="output"></span></p>
   
      <h2>endsWith() Method</h2>
      <button id="endsWithBtn">Check if the text ends with "World!"</button>
      <p>Result: <span id="endsWithOutput" class="output"></span></p>
   
      <h2>search() Method</h2>
      <input type="text" id="searchTerm" placeholder="Enter search term">
      <button id="searchBtn">Search</button>
      <p>Result: <span id="searchOutput" class="output"></span></p>
   
      <h2>indexOf() Method</h2>
      <input type="text" id="indexOfTerm" placeholder="Enter search term">
      <button id="indexOfBtn">Find index</button>
      <p>Result: <span id="indexOfOutput" class="output"></span></p>
   
      <h2>substring() Method</h2>
      <input type="text" id="substringStart" placeholder="Enter start index">
      <input type="text" id="substringEnd" placeholder="Enter end index">
      <button id="substringBtn">Get substring</button>
      <p>Result: <span id="substringOutput" class="output"></span></p>
   
      <h2>substr() Method</h2>
      <input type="text" id="substrStart" placeholder="Enter start index">
      <input type="text" id="substrLength" placeholder="Enter length">
      <button id="substrBtn">Get substring</button>
      <p>Result: <span id="substrOutput" class="output"></span></p>
   
      <h2>slice() Method</h2>
      <input type="text" id="sliceStart" placeholder="Enter start index">
      <input type="text" id="sliceEnd" placeholder="Enter end index">
      <button id="sliceBtn">Get slice</button>
      <p>Result: <span id="sliceOutput" class="output"></span></p>
   </div>
</body>
</html>

Explanation

The HTML script that is provided initializes a text variable with the value "Hello, World!" and outputs it on the website using JavaScript. It creates button event handlers that correlate to various jQuery functions. These buttons' respective methods are triggered when they are clicked, and the output components show the outcomes. The "Hello" character is the first character that the startsWith() method looks for. The endsWith() method determines whether the string ends with "World!" When a user-provided phrase is searched for within text, the search() method provides the index of the first occurrence. The index of a user-provided phrase within text can be found using the indexOf() method. Using user-provided start and end indices, the substring(), substr(), and slice() functions extract substrings from text. In general, the webpage's text variable is manipulated and examined using jQuery techniques and JavaScript code, which also allows for user involvement.

Conclusion

  • JavaScript provides a range of string functions to verify whether a string is a substring of another string.

  • The JavaScript str.startsWith() method is employed to check if the specified string starts with the characters from the provided string. This method is case-sensitive, meaning it distinguishes between uppercase and lowercase letters.

  • JavaScript utilizes the str.endsWith() function to determine whether the given string ends with the characters from the supplied string or not.

  • JavaScript provides a built-in method called string.search() that is used to search for a match between a given string object and a regular expression.

  • JavaScript's str.indexOf() function finds the index of the first occurrence of the supplied string argument within the supplied string. The result is zero-based.

  • The JavaScript function string.substring() retrieves a portion of the supplied string, starting at the start index and ending at the end index. Indexing starts at position zero.

  • The JavaScript str.substr() method extracts a predetermined amount of characters starting at the predetermined index from the provided string. In essence, this technique extracts a section of the original string.

  • A piece or slice of the given input string can be extracted using the JavaScript string.slice() method, which returns the extracted portion as a new string.

Updated on: 19-Jul-2023

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements