1.

What is the "double tilde" (~~) operator in JavaScript?

Answer»

The substr() and substring() methods are simpler, yet they have some differences. The 2nd argument of the substring() method is the index to halt the search, whereas the 2nd parameter of substr() is the maximum length.

Note: We will be taking the same string and the same parameter value for both the functions to make it easier to understand

substr() method

The substr() method returns the characters in a string BEGINNING at the specified location. It goes through the number of characters which is specified by the user.

The parameters of substr(start, len):

  • start − Location start extracting characters.
  • length − The count of characters to extract.

Let us see an example.

We have the following string:

var myStr = "Knowledge Hut!";

Now, we will use substr() as discusses above with the parameters to GET 5 elements beginning from 3rd index:

myStr.substr(3,5)

The example: 

<html>    <head>       <TITLE>JavaScript substr()</title>    </head>    <body>       <script>          var myStr = "Knowledge Hut!";          document.write("(3,5): " + myStr.substr(3,5));       </script>    </body> </html>

The output from 3rd index.

5 is the length of elements after beginning with 3rd index:

(3,5): wledg

substring() method

The substring() method returns subset of a string.

The parameters of substring(i1, i2):

  • i1 – Index from where you WANT the substring.
  • i2 − Index till when you want the substring.

Let us see an example.

We have the following string:

var myStr = "Knowledge Hut!";

Now, we will use substring() as discussed above with the parameters to get substring from 3 to 5, since we set the parameter as 3 and 5:

myStr.substring(3,5)

The example: 

<html>    <head>       <title>JavaScript substr()</title>    </head>    <body>       <script>          var myStr = "Knowledge Hut!";          document.write("(3,5): " + myStr.substring(3,5));       </script>    </body> </html>

The output from substring 3 to 5: 

(3,5): wl


Discussion

No Comment Found