Home  >  Article  >  Web Front-end  >  How to check if a string starts/ends with a specific string in jQuery?

How to check if a string starts/ends with a specific string in jQuery?

WBOY
WBOYforward
2023-08-24 12:45:10881browse

如何在 jQuery 中检查字符串以特定字符串开头/结尾?

JavaScript’s relationship with HTML/CSS files, specifically with the Document Object Model (DOM), is made easier with the open source library called “jQuery”. Traversing and manipulating HTML files, controlling browser events, generating DOM visuals, facilitating Ajax connections, and cross-platform JavaScript programming are all made easier with this package.

To verify whether a specific string forms a substring of another string, JavaScript provides a variety of string functions. Therefore, jQuery is dispensable for this task.

Nonetheless, we will illustrate the various ways to verify whether a string starts or ends with another string:

  • startsWith() and endsWith() methods

  • search() method

  • indexOf() method

  • substring() method

  • substr() method

  • slice() method

Suppose we have a string, str = "Hi, how are you?" Our task is to determine whether it starts with startword = "Hi" and ends with endword = "?"

Method 1-str.startsWith()

The str.startsWith() method in JavaScript is used to verify whether the characters in the given string are the beginning of the specified string. This technique is case-sensitive, meaning it distinguishes between uppercase letters and lowercase letters.

The above method admits two parameters, as mentioned before, as follows:

  • searchString: constitutes a mandatory parameter and stores the string to be searched.

  • start: It establishes the position in the supplied string from which searchString is to be found. The default value is zero.

grammar

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 whether the supplied string ends with a character in another string, use the JavaScript method str.endsWith().

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

  • searchString: Indicates the string that needs to be found at the end of the given string.

  • length: The length parameter determines the size of the original string against which the search string is checked.

When this function is executed, if searchString is found, the Boolean value true is returned; otherwise, false is returned.

Example

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

Output

false

Method 3 - string.search()

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

grammar

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 finds the index of the first instance of the supplied string parameter in the given string. The result starts from 0.

grammar

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()

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

grammar

string.substring(Startindex, Endindex)

Parameters Startindex and Endindex determine the string segment to be extracted as a substring. The Endindex parameter is optional.

When the string.substring() function is executed, it creates a new string that represents a part 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 a given string starting at a specified index. This method effectively extracts a segment of the original string.

grammar

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()

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

grammar

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>

illustrate

The provided HTML script initializes the text variable with the value "Hello, World!" and use JavaScript to output it to the website. It creates button event handlers associated with various jQuery functions. The respective methods of these buttons are triggered when clicked, and the output component displays the results. The "Hello" character is the first character that the startsWith() method looks for. The endsWith() method determines whether the string ends with "World!" When searching text for a user-supplied phrase, the search() method provides an index of the first occurrence. The index of a user-supplied phrase in the text can be found using the indexOf() method. The substring(), substr(), and slice() functions extract substrings from text using user-supplied start and end indices. Generally, text variables of web pages are manipulated and inspected using jQuery technology and JavaScript code, which also allows user participation.

in conclusion

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

  • JavaScript str.startsWith() method is used to check whether the specified string starts with the characters in the provided string. This method is case sensitive, which means it distinguishes between uppercase and lowercase letters.

  • JavaScript uses the str.endsWith() function to determine whether a given string ends with a character in the provided string.

  • JavaScript provides a built-in method called string.search() for searching for matches 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 parameter in the supplied string. The result is ground zero.

  • 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.

  • JavaScript str.substr() method extracts a predetermined number of characters from the provided string starting at a predetermined index. Essentially, this technique extracts a portion of the original string.

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

The above is the detailed content of How to check if a string starts/ends with a specific string in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete