Friday, March 13, 2020

Learn about the 19 important JavaScript String Methods you should know with proper examples



Hello guys! evening and welcome to this new section of my tutorial on JavaScript. In my previous tutorial post, we discussed about how to implement JavaScript String Properties. In this section of my tutorial, i will be moving on to a more interesting topic. In this tutorial post we will be using few examples to illustrate how to implement the String methods.

String - charAt() Method

charAt() is a method that returns the character from the specified index.

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string, called stringName is stringName.length - 1.

Syntax

Use the following syntax to find the character at a particular index.

string.charAt( index );

Argument Details

Index - An integer between 0 and 1 less than the length of the string.

Return Value

Returns the character from the specified index.

Example

Try the following example below.

<html>
     <head>
          <title>JavaScript String charAt() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = new String ("This is a string");
               document.write("str.charAt(0) is: " + str.charAt(0) + "<br />" );              
               document.write("str.charAt(1) is: " + str.charAt(1) + "<br />" );
               document.write("str.charAt(2) is: " + str.charAt(2) + "<br />" );
               document.write("str.charAt(3) is: " + str.charAt(3) + "<br />" );
               document.write("str.charAt(4) is: " + str.charAt(4) + "<br />" );
               document.write("str.charAt(5) is: " + str.charAt(5) + "<br />" );
          </script>
     </body>
</html>

Output

Below is the output of the above example.

str.charAt(0) is:  T
str.charAt(1) is:  h
str.charAt(2) is:  i
str.charAt(3) is:  s
str.charAt(4) is:
str.charAt(5) is:  i

You can also read our tutorial post on: Css Positioning


String - charCodeAt() Method

This method returns a number indicating the Unicode value of the character at the given index.

Unicode code points range from 0 to 1,114,111. This first 128 Unicode code points are a direct match of the ASCII character encoding. charCodeAt() always returns a value that is less than 65,536.

Syntax

Use the following syntax to find the character code at a particular index.

string.charCodeAt(index);

Argument Details

Index - An integer between 0 and 1 less than the length of the string; if unspecified, defaults to 0.

Return Value

Returns a number indicating the Unicode value of the character at the given index. It returns NaN (Not a Number) if the given index is not between 0 and 1 less than the length of the string.

Example

Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String charCodeAt() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = new String ("This is a string");
               document.write("str.charCodeAt(0) is: " + str.charCodeAt(0) + "<br />" );              
               document.write("str.charCodeAt(1) is: " + str.charCodeAt(1) + "<br />" );
               document.write("str.charCodeAt(2) is: " + str.charCodeAt(2) + "<br />" );
               document.write("str.charCodeAt(3) is: " + str.charCodeAt(3) + "<br />" );
               document.write("str.charCodeAt(4) is: " + str.charCodeAt(4) + "<br />" );
               document.write("str.charCodeAt(5) is: " + str.charCodeAt(5) + "<br />" );
          </script>
     </body>
</html>

Output

Below is the output of the above example.

str.charCodeAt(0) is:  84
str.charCodeAt(1) is:  104
str.charCodeAt(2) is:  105
str.charCodeAt(3) is:  115
str.charCodeAt(4) is:  32
str.charCodeAt(5) is:  105

You can also read our tutorial post on: Css Media types

String - concat() Method

This method adds two or more strings and returns a new single string.

Syntax

It's syntax is as follows :

string.concat(string2,      string3,      string4[ , .......  ,  stringN]);         

Argument Details

string2........stringN - These are the strings to be concatenated.

Return Value

Returns a single concatenated string.

Example

Try the following example below for better understanding and feel free to ask your questions via the comment box below.

<html>
     <head>
          <title>JavaScript String concat() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str1 = new String ("This is string one");
               var  str2 = new String ("This is string two");
               var  str3 = str1.concat ( str2 );
               document.write("Concatenated String is: " + str3);
          </script>
     </body>
</html>

Output

Below is the output of the above example.

Concatenated String is: This is string oneThis is string two 

You can also check out one of our tutorials on: How to implement the various JavaScript Number methods with examples


String - indexOf() Method

This method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.

Syntax

Use the following syntax below in other to implement the indexOf() method.

string.indexOf (searchValue[ ,       fromIndex])

Argument Details

  • searchValue - A string value representing the value to search for.
  • fromIndex - The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.

Return Value

Returns the index of the found occurrence, otherwise -1 if not found.

Example

Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String indexOf() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str1 = new String ("This is string one");
               var  index = str1.indexOf( "string" );
               document.write("indexOf found String : " + index + "<br />" );        

               var  index = str1.indexOf( "one" );
               document.write("indexOf found String : " + index );
          </script>
     </body>
</html>

Output

Below is the output of the above example. Make sure you also practice yourselves and always feel free to ask your questions via the comment box below.

indexOf found String : 8
indexOf found String : 15

You can also read our tutorial post on: Css margin

String - lastIndexOf() Method

This method returns the index within the calling String object of the last occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.

Syntax

Use the following syntax below in other to implement the lastIndexOf() method.

string.lastIndexOf (searchValue[ ,       fromIndex])

Argument Details

  • searchValue - A string value representing the value to search for.
  • fromIndex - The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.

Return Value

Returns the index of the last found occurrence, otherwise -1 if not found.

Example

Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String lastIndexOf() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str1 = new String ("This is string one and again string ");
               var  index = str1.lastIndexOf( "string" );
               document.write("lastIndexOf found String : " + index + "<br />" );        

               var  index = str1.lastIndexOf( "one" );
               document.write("lastIndexOf found String : " + index );
          </script>
     </body>
</html>

Output

Below is the output of the above example. Make sure you also practice yourselves and always feel free to ask your questions via the comment box below.

lastIndexOf found String : 29
lastIndexOf found String : 15

You can also check out our tutorial post on: JavaScript Event tutorial with examples

String - localeCompare() Method

This method returns a number indicating whether a reference string comes before or after or is the same as the given string in sorted order.

Syntax

The following code below is the syntax of localeCompare() method:

string.localeCompare( param )

Argument Details

param - A string to be compared with string object.

Return Value

  • 0 - If the string matches 100%.
  • 1 - no match found, and the parameter value comes before the string object's value in the locale sort order. 
  • -1 - no match found, and the parameter value comes after the string object's value in the locale sort order. 

Example

Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String localeCompare() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str1 = new String ("This is a very simple string ");
               var  index = str1.localeCompare( "IJK" );
               document.write("localeCompare first : " + index + "<br />" );        

               var  index = str1.localeCompare( "ABCD   ?" );
               document.write("localeCompare second : " + index );
          </script>
     </body>
</html>

Output

Below is the output of the above example.

localeCompare first : -1
localeCompare second : 1

You can also check out one of our tutorial post on: Css Images


String - match Method

This method is used to retrieve the matches when matching a string against a regular expression.

Syntax

Use the following syntax below to implement the match() method.

string.match( param) 

Argument Details

param - A regular expression object.

Return Value

  • If the regular expression includes the g flag, the method returns an Array containing all the matches.

Example

Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String match() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = "For more information, see Chapter 3.4.5.1";          
               var  re = /(chapter  \d+(\.\d)*)/i; 
               var  found = str.match( re); 
               document.write( found);
          </script>
     </body>
</html>

Output

Below is the output of the above example.

Chapter 3.4.5.1, Chapter 3.4.5.1, .1

You can also read our tutorial post on: JavaScript if.....else Statement

String - replace() Method

This method finds a match between a regular expression and a string, and replaces the matched substring with a new substring.

The replacement string can include the following special replacement patterns:

PatternInserts
$$Inserts a "$".
$&Inserts the matched substring.
                        $`Inserts the portion of the string that precedes the matched substring.
$'Inserts the portion of the string that follows the matched substring.
                 $n or $nnWhere n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.

Syntax

The syntax to use the replace() method is as follows:

string.replace(regexp/substr ,   newSubStr/function[ ,  flags]);     

Argument Details

  • regexp - A RegExp object. The match is replaced by the return value of parameter #2
  • substr - A String that is to be replaced by newSubStr.
  • newSubStr - The String that replaces the substring received from parameter #1.
  • function - A function to be invoked to create the new substring.
  • flags - A String containing any combination of the RegExp flags: g - global match, i - ignore case, m - match over multiple lines. This parameter is only used if the first parameter is a string.

Return Value

It simply returns a new changed string.

Example

Try the following example below.

<html>
     <head>
          <title>JavaScript String replace() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  re = /apples/gi ;
               var  str = "Apples are round, and apples are juicy.";
               var  newstr = str.replace(re,    "oranges");
               document.write (newstr);
          </script>
     </body>
</html>

Output

Below is the output of the above example.

oranges are round, and oranges are juicy.

Example

Try the following example, it shows how to  switch words in a string.

<html>
     <head>
          <title>JavaScript String replace() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  re = /(\w+)\s(\w+)/;
               var  str = "nkpara  kennedy" ;
               var  newstr = str.replace(re,    "$2,   $1");
               document.write (newstr);
          </script>
     </body>
</html>

Output

Below is the output of the above example.

Kennedy , nkpara 

You can also read our tutorial post on: Css Text

String - search() Method

This method executes the search for a match between a regular expression and this String object.

Syntax

Its syntax is as follows:

string.search( regexp );

Argument Details

regexp - A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).

Return Value

If successful, the search returns the index of the regular expression inside the string. Otherwise, it returns -1.

Example

Try the following example below for better understanding and feel free to ask your questions via the comment box below

<html>
     <head>
          <title>JavaScript String search() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  re = /apples/gi ;
               var  str = "Apples are round, and apples are juicy.";

               if  ( str.search(re) == -1 )   {
                   document.write("Does not contain Apples");
               }  else  {
                   document.write("Contains Apples");
               }
          </script>
     </body>
</html>

Output

Below is the output of the above example.

Contains Apples 

You can also check out one of our tutorials on: What is JavaScript?


String - slice() Method

This method extracts a section of a string and returns a new string.

Syntax

Its syntax is as follows:

string.slice( beginslice  [,      endSlice] );

Argument Details

  • endSlice - The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string.

Return Value

If successful, slice returns the index of the regular expression inside the string. Otherwise, it returns -1.

Example

Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String slice() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = "Apples are round, and apples are juicy.";
               var  sliced = str.slice(3,   -2);
               document.write( sliced ); 
          </script>
     </body>
</html>

Output

Below is the output of the above example.

les are round, and apples are juic

You can also read our tutorial post on: Css Inclusion

String - split() Method

This method splits a string object into an array of strings by separating the string into substrings.

Syntax

Its syntax is as follows:

string.split( [separator] [,    limit] );

Argument Details

  • separator - Specifies the character to use for separating the string. If separator is omitted, the array returned contains one consisting of the entire string.
  • limit - Integer specifying a limit on the number of splits to be found.

Return Value

The split method returns the new array. Also, when the string is empty, split returns an array containing one empty string, rather than an empty array.

Example

Try the following example below for better understanding and feel free to drop your questions via the comment box below

<html>
     <head>
          <title>JavaScript String split() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = "Apples are round, and apples are juicy.";
               var  splitted = str.split("  " ,  3);
               document.write( splitted ); 
          </script>
     </body>
</html>

Output

Below is the output of the above example.

Apples, are, round, 

String - substr() Method

This method returns the characters in a string beginning at the specified location(point) through the specified number of characters.

Syntax

The syntax to use substr() is as follows:

string.substr(start [,    length] );

Argument Details

  • start - Location at which to start extracting characters (an integer between 0 and one less than the length of the string).
  • length - The number of characters to extract.

Note - If start is negative, substr uses it as a character index from the end of the string.

Return Value

The substr() method returns the new sub-string based on a set of given parameters.

Example

Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String substr() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = "Apples are round, and apples are juicy.";
               document.write("(1, 2):  "     + str.substr(1, 2)     +  "<br />" );      
               document.write("(-2, 2): "     + str.substr(-2, 2)    +  "<br />" );
               document.write("(1): "          + str.substr(1)          +  "<br />" );
               document.write("(-20, 2): "   + str.substr(-20, 2)  +  "<br />" );
               document.write("(20,  2): "   + str.substr(20,  2) );
          </script>
     </body>
</html>

Output

Below is the output of the above example.

(1, 2):  pp
(-2, 2):  y. 
(1):  pples are round, and apples are juicy.
(-20, 2):  nd
(20,  2):  d

You can also read our tutorial post on: Data Type Part Two


String - substring() Method

This method returns a subset of a String object.

Syntax

The syntax to use substr() method is as follows:

string.substring(indexA,    [indexB] )

Argument Details

  • indexA - An integer between 0 and one less than the length of the string.
  • indexB - (optional) An integer between 0 and the length of the string.

Return Value

The substring method returns the new sub-string based on given parameters.

Example

Try the following example below.

<html>
     <head>
          <title>JavaScript String substring() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = "Apples are round, and apples are juicy.";
               document.write("(1, 2):   "     + str.substring(1, 2)       +  "<br />" );      
               document.write("(0, 10): "     + str.substring(0, 10)    +  "<br />" );
               document.write("(5):       "     + str.substring(5) );
          </script>
     </body>
</html>

Output

Below is the output of the above example.

(1, 2):  p
(0, 10):  Apples are 
(5):  s are round, and apples are juicy.

You can also check out one of our tutorials on: How to implement JavaScript functions in your program

String - toLocaleLowerCase() Method

This method is used to convert the characters within a string to lowercase while respecting the current locale. For most languages, it returns the same output as toLowerCase.

Syntax

Its syntax is as follows:

string.toLocaleLowerCase()

Return Value

Returns a string in lowercase with the current locale.

Example

Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String toLocaleLowerCase() Method</title>
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = "Apples are round, and apples are juicy.";
               document.write(str.toLocaleLowerCase() );
          </script>
     </body>
</html>

Output

Below is the output of the above example.

apples are round, and apples are juicy.

String - toLocaleUpperCase() Method

This method is used to convert the characters within a string to uppercase while respecting the current locale. For most languages, it returns the same output as toUpperCase.

Syntax

Its syntax is as follows:

string.toLocaleUpperCase()

Return Value

Returns a string in uppercase with the current locale.

Example

Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String toLocaleUpperCase() Method</title>    
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = "Apples are round, and apples are juicy.";
               document.write(str.toLocaleUpperCase() );
          </script>
     </body>
</html>

Output

Below is the output of the above example.

APPLES ARE ROUND, AND APPLES ARE JUICY.

You can also read our tutorial post on: Css Syntax


String - toLowerCase Method
This method returns the calling string value converted to lowercase.

Syntax
Its syntax is as follows:

string.toLowerCase()

Return Value
Returns the calling string value converted to lowercase.

Example
Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String toLowerCase() Method</title>    
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = "Apples are round, and Apples are juicy.";
               document.write(str.toLowerCase() );
          </script>
     </body>
</html>

Output
Below is the output of the above example.

apples are round, and apples are juicy.

String - toString() Method
This method returns a string representing the specified object.

Syntax
Its syntax is as follows:

string.toString()

Return Value
Returns a string representing the specified object. 

Example
Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String toString() Method</title>    
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = "Apples are round, and Apples are juicy.";
               document.write(str.toString() );
          </script>
     </body>
</html>

Output
Below is the output of the above example.

Apples are round, and Apples are juicy.

You can also read our tutorial post on: Data Type Part 1

String - toUpperCase() Method
This method returns the calling string value converted to uppercase.

Syntax
Its syntax is as follows:

string.toUpperCase()

Return Value
Returns the calling string value converted to uppercase.

Example
Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String toUpperCase() Method</title>    
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = "Apples are round, and Apples are juicy.";
               document.write(str.toUpperCase() );
          </script>
     </body>
</html>

Output
Below is the output of the above example.

APPLES ARE ROUND, AND APPLES ARE JUICY.



String - valueOf() Method
This method returns the primitive value of a String object.

Syntax
Its syntax is as follows:

string.valueOf()

Return Value
Returns the primitive value of a String object.

Example
Try the following example below for better understanding.

<html>
     <head>
          <title>JavaScript String valueOf() Method</title>    
     </head>

     <body>
          <script  type = "text/Javascript">
               var  str = new String("Hello World");
               document.write(str.valueOf() );
          </script>
     </body>
</html>

Output
Below is the output of the above example.

Hello World 

Alright guys! we have come to the end of this wonderful tutorial post on JavaScript. In my next tutorial, am going to be using few examples to demonstrate the usage of String HTML Wrappers. Feel free to drop your questions via the comment box below, they will be attended to as soon as possible.

Follow us on our various social media handles to stay updated with our latest tutorials. You can also subscribe to our newsletter to get our tutorials delivered directly to your emails. Thanks for reading and bye for now.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.