Wednesday, October 14, 2026
HomeArtificial IntelligenceWhat's a Javascript Substring? Variants, Makes use of and extra

What’s a Javascript Substring? Variants, Makes use of and extra

[ad_1]

javascript substring

What’s a string?

A string is a assortment of a collection of characters that’s used to signify textual content. For instance: “Good day World”.

What’s a Substring in Javascript?

A substring is a small a part of a string or a subset of a string. A substring is a contiguous sequence of characters in a string. For instance: “Good day” is a substring of the string “Good day World”. 

Substring in Javascript is an inbuilt operate that’s generally used to return part of a given string that can be utilized to create smaller strings from the larger string. Javascript’s strings are immutable, i.e., the unique string stays the identical, and the strategy returns a brand new string each time. It doesn’t edit or make adjustments to the unique string. 

The Substring(int startIndex, int endIndex) technique returns a brand new string which is a substring of that enter string we supplied between the beginning index and finish index with the indexes ranging from zero(0). 

In easy language, after we present any string or an entire sentence, it merely returns part of that sentence, whether or not it’s a phrase or a mixture of some phrases from that sentence or string. The substring technique begins on the specified index quantity, and the strategy finds the character at that index quantity and returns it upto the ending index quantity, which we supplied as parameters in our technique. 

The explanation behind its use is that it creates smaller strings from bigger strings. As we all know that strings are immutable, and the unique string stays the identical as it’s however the substring strategies that we use to return a brand new string and the previous or enter string stay the identical. 

Syntax:

String.substring(start_index, end_index)

Substring parameters start_index and end_index outline the a part of the string that’s taken as a substring. The end_index could be optionally available. 

This technique returns a brand new string that’s a part of the given string. 

Variants of Substring in Javascript:

We have now two variants of the substring() technique in Javascript, that are described under:

  1. Variant 1:

Given the beginning index the returned substring contains​ characters ranging from the required begin index of the enter string, till the tip of the string.

string.substring(var startIndex)

For instance:

<!DOCTYPE html>
<html>
  <head>
<title> Variants of substring in javascript</title>
    </head>
<physique>
<p>Click on to get the substring out of 'Good day World'.</p>
<script>
  operate myFunc() {
  var str = "Good day World";
  var substr = str.substring(3);
  doc.getElementById("demo").innerHTML = substr;
}
</script>
<button onclick="myFunc()">Attempt Me!</button>
<p id="demo"></p>
</physique>
</html>

Output: lo World

Because the index begins with 0, Hel takes index 0,1,2, and the output is displayed ranging from index 3, as talked about within the begin index of the substring.

  1. Variant 2:

Right here we specify each the beginning index and the tip index. The returned substring can have characters together with and between the given indexes. The character firstly index is included within the substring, and the character on the finish index is excluded. So, the characters within the extracted substring start from the beginning index until the tip index-1.

string.substring(var startIndex, var endIndex)

For instance:

<!DOCTYPE html>
<html>
<head>
<title> Variants of substring in javascript</title>
    	</head>
<physique>
<p>Click on to get the substring out of 'Good day World'.</p>
<script>
  operate myFunc() {
  var str = "Good day World";
  var substr = str.substring(1,6);
  doc.getElementById("demo").innerHTML = substr;
}
  </script>
<button onclick="myFunc()">Attempt Me!</button>
<p id="demo"></p>
</physique>
</html>

Output: ello. 

The beginning index and finish index are given. therefore the resultant substring begins with the beginning index and  ends with index-1

Use and Functions of Substring:

Substring in javascript is a string manipulation operate that may manipulate all string information varieties corresponding to BIT, CHARACTER, and BLOB and may extract characters from a string and create a brand new string. It has many purposes, corresponding to suffix and prefix extraction.

  • Allow us to take an instance if you wish to extract a reputation from a string of textual content or the final title from a given string. You are able to do all this by way of the Substring technique in Javascript. The demonstration of this instance in code is under:
<script>
 	var str = "Good day World";
var substr = str.substring(4);
  	console.log(“The unique string is:”);
console.log(substr);
</script>

Output:

The unique string is: Good day World

The extracted substring is: o World

  • The Substring technique can also be helpful to test if a given string is palindrome or not such that the Substring technique reads the string the identical manner from each ends. To higher perceive, see the instance under:

Javascript operate to test if the string is palindrome or not.

operate checkPalin(string) {
    // string.size is used to search out the size of a string
    const len = string.size;
    // looping by means of half of the string
    for (let i = 0; i < len / 2; i++) {
    // her we're checking if first and final string are similar
        if (string[i] !== string[len - 1 - i]) {
            return 'String shouldn't be a palindrome';
        }
    }
    return 'String is a palindrome';
}
// take enter from person
const string = immediate('Enter a string to test for palindrome: ');

// operate name
const worth = checkPalin(string);
console.log(worth);

Output:

Enter a string: Good day

String shouldn’t be a palindrome

  • The substring technique could be very helpful for getting all substrings of a string. 

The javascript code is as follows:

<script>
        // This operate will print all substring from a given string
        operate SubString( stri , n)
        {
        for (var i = 0; i < n; i++)
            for (var j = i+1; j <= n; j++)
            doc.write(stri.substring(i, j)+"<br/>");
        }
            var stri = "abcd";
            SubString(stri, stri.size);
</script>

Output:

a

ab

abc

abcd

b

bc

bcd

c

cd

d

Methods to use Substring with size Property in JavaScript:

The size property in javascript is used to get the size of a string. The substring() technique of javascript and size property are used collectively to extract the final characters of a selected string. This  inbuilt technique is less complicated to recollect and use as you don’t have to know the beginning and ending indices.

Allow us to see an instance under to know higher how it may be used:

Instance:

var theString = “GreatLearning”;
var theString1 = theString.substring(theString.size – 8 ); // Shows final 8 characters of theString “GreatLearning”
console.log(theString1);

OUTPUT:

Studying

Within the above instance, we didn’t have to enter the beginning and ending index of the string, and we simply entered the size of the substring that we would have liked in our end result. So it returned 8 characters, and it returned the substring from the tip as we used the (-) signal earlier than 8 whereas specifying parameters. 

substring() vs substr() in JavaScript.

The distinction between the substring() and substr() JavaScript string strategies is that substring() takes a beginning index and an finish index, whereas substr takes solely a beginning index and a size of characters.

String.prototype.substring

The substring() technique returns a brand new string which is a subset of the particular string. Takes up one or two arguments. With one argument given, we get the string ranging from the required index (inclusive) till the tip of the string:

const myStr="Studying";

const myNewStr = myStr.substring(2);

console.log(myNewStr); 

OUTPUT:

arning

With two arguments given, we get a subset of the string from the beginning index to the tip index (unique):

const myString = 'Studying';

const myNewStr = myString.substring(0, 3);

console.log(myNewStr);

Output:

Lea

String.prototype.substr

The substr() technique could be very related, however the second argument is for the variety of characters and never for the tip index.

Right here we wish a 4-character string from a beginning index of three:

const myString = 'GreatLearning';

const myNewStr = myString.substr(3, 4);

console.log(myNewStr); 

OUTPUT: atLe

Destructive begin index

The primary argument to substr can take up a destructive integer. On this case, the beginning of the returned string is counted from the tip of the string that the strategy is used on:

const myString = 'LearningAlligator';

const myNewStr = myString.substr(-3);

console.log(myNewStr); 

Output:

gni

Similar Outcome When Solely One Argument

If just one optimistic integer is used as an argument, then each substring and substr return the identical worth:

const myString = 'GreartLearning';

const myNewSubstring = myString.substring(4);

const myNewSubstr = myString.substr(4);

console.log(myNewSubstring); 

console.log(myNewSubstr); 

Output:

rtLearning

rtLearning

slice( ) Methodology

The slice( ) technique is just like the substring( ) technique, and it returns a substring of the unique string. The slice technique takes two arguments

SYNTAX:

string.slice(startIndex, endIndex);

The place:

startIndex: refers to the start line of the substring

endIndex: refers back to the ending level of the substring (optionally available)

The commonalities between substring( ) and slice( ) strategies:

  • If we don’t give the ending index, then we get a substring ranging from the given index quantity till the tip of the unique string
  • If we give each the startIndex and the endIndex, then we’ll get the characters between the given index numbers of the unique string.
  • If startIndex and endIndex are larger than the size of the string, it returns an empty string.

Variations of the slice( ) technique:

  • If startIndex is bigger than the endIndex, the slice( ) technique returns an empty string.
  • If startIndex is given a destructive quantity, then the primary character begins from the tip of the string, i.e., the reverse of the string.

Word: We are able to use the slice( ) technique additionally for JavaScript arrays. Yow will discover right here my different article concerning the slice technique to see the utilization for arrays.

Vital Factors on JavaScript subString: 

  • The JavaScript substring() technique extracts the symbols between two indexes and returns an information string which is a subset of the unique string.
  • substring() technique extracts the symbols in a string between finish and begin and doesn’t embrace the tip itself.
  • If the tip index has a smaller worth than the beginning, the arguments will probably be switched.
  • If both the tip index or begin index is given as a destructive quantity, the worth is 0.
  • The unique string stays unchanged after utilizing the substring() technique.

Listed here are some examples that you could attempt your self to know the idea of JavaScript SubString fully:

<html>
   <head>
      <title>Nice Studying JavaScript String substring() Methodology</title>
   </head>
   
   <physique>   
      <script sort = "textual content/javascript">
        var string = "Apples are pink or inexperienced in colour and spherical";    
        doc.write("(4): "    + string.substring(4));   
        doc.write("<br />");  
        doc.write("(2,3): "    + string.substring(2,3));
        doc.write("<br />(0,8): "   + string.substring(0, 8));
        doc.write("<br />(-5): "      + string.substring(-5));
        doc.write("<br />");
        doc.write("(2,3): "    + string.slice(2,3));
     </script>
   </physique>
</html>

OUTPUT:

(4): es are pink or inexperienced in colour and spherical

(2,3): p

(0,8): Apples a

(-5): Apples are pink or inexperienced in colour and spherical

(2,3): p

Conclusion:

Inspecting and manipulating is a standard job carried out by most programming languages, particularly with user-facing code. For numerous causes, corresponding to validating strings, you’ll have to test if a string comprises a substring. There are 3 totally different strategies, substring(), substr(), and slice(), supplied by Javascript that permits us to validate a string and extract what’s required with out altering the unique string.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments