Wednesday, January 31, 2018

String and Regular Expression Object in JavaScript




Hi, I Ankita Saini pursuing JavaScript course from ADMEC Multimedia Institute. String and Regular expression object was the topic of my last JavaScript class. So, I decided to share my knowledge with you as it is an important topic. So, let’s start with an introduction of string object.


String Object:

In JavaScript Strings are mainly used for storing and for manipulating the text like “Nitya Sharma”. String can be any text inside the quotes and the quotes can be single as well as double quotes. Also, we can use quotes inside the string but the condition is that the quotes surrounding the string should not match the quotes inside the string.

A String Object allows us to work with a series of characters and it wraps the JavaScript string using a number of methods.

Properties of String: -
A String Object has these properties:
•    Constructor – A constructor returns a reference to the String function.
•    Length – Length property returns the length of the String.
Ex –
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<html>
   <head>
      <title>JavaScript String Length Property</title>
   </head>
   <body>
      <script type="text/javascript">
         var str = new String( "This is string" );
         document.write("str.length is:" + str.length); 
      </script>
   </body>
</html>
  • Prototype – A prototype property allows us to add properties and methods to an object.
String Methods: -
Here are few String Methods which are mainly used in JavaScript:

Finding a String into a String – Two methods comes under this:
1.    IndexOf()
2.    LastIndexOf()

IndexOf() – This method returns the index of the first occurrence of a particular text in a String:
Ex:-
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<!DOCTYPE html>
<html>
<body>
     <h2>JavaScript String Methods</h2>
     <p id="demo"></p>
     <script>
          var str = "Please locate where 'locate' occurs!";
          var pos = str.indexOf("locate");
          document.getElementById("demo").innerHTML = pos;
     </script>
</body>
</html>

Output:
This method returns the position of the first occurrence of a specified text and that is : 7

lastIndexOf() – It is as same as IndexOf, only it starts from the right and moves left:
Ex:-
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Ex:-
<!DOCTYPE html>
<html>
<body>
   <h2>JavaScript String Methods</h2>
   <p>The lastIndexOf() method returns the position of the last occurrence of a specified text:</p>
   <p id="demo"></p>
   <script>
       var str = "Please locate where 'locate' occurs!";
       var pos = str.lastIndexOf("locate");
       document.getElementById("demo").innerHTML = pos;
   </script>
</body>
</html>

Output:
This method returns the position of the last occurrence of the specified text and that is: 21

search(): - The Search method searches the string for a specified value and returns its position
Ex:-
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE html>
<html>
<body>
   <h2>JavaScript String Methods</h2>
   <p>The search() method returns the position of the first occurrence of a specified text in a string:</p>
   <p id="demo"></p>
   <script>
       var str = "Please locate where 'locate' occurs!";
       var pos = str.search("locate");
       document.getElementById("demo").innerHTML = pos;
   </script>
</body>
</html>

Output:
This method returns the position of the first occurrence of a specified text in the string and that is: 7

Extracting String Methods:
We use three methods for extracting a part of string:
1.    Slice Method
2.    substring Method
3.    substr Method

slice()– This method extracts a part of String and it returns a extracted part in a new string. This method uses two parameters the starting position and the ending position.
Ex:-
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE html>
<html>
<body>
   <h2>JavaScript String Methods</h2>
   <p>The slice() method extract a part of a string and returns the extracted parts in a new string:</p>
   <p id="demo"></p>
   <script>
       var str = "Apple, Banana, Kiwi";
       var res = str.slice(7,13);
       document.getElementById("demo").innerHTML = res;
   </script>
</body>
</html>

Output:
This method extracts a part of the string and returns the extracted part of the string as a new string and that is “Banana”

substring() - This method is as same as the Slice Method, the only difference is that it does not accept negative indexes.
Ex:-
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE html>
<html>
<body>
   <h2>JavaScript String Methods</h2>
   <p>The substr() method extract a part of a string and returns the extracted parts in a new string:</p>
   <p id="demo"></p>
   <script>
       var str = "Apple, Banana, Kiwi";
       var res = str.substring(7,13);
       document.getElementById("demo").innerHTML = res;
   </script>
</body>
</html>

Output:
This method extracts a part of the string and returns the extracted part in a new string and that is: “Banana”

replace(): - This method replaces the specified value with another value in a string:
Ex:-
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<body>
   <h2>JavaScript String Methods</h2>
   <p>Replace "Microsoft" with "Google" in the paragraph below:</p>
   <button onclick="myFunction()">Plz Click</button>
   <p id="demo">Please visit Microsoft!</p>
 
   <script>
       function myFunction() {
          var str = document.getElementById("demo").innerHTML;
          var txt = str.replace("Microsoft","Google");
          document.getElementById("demo").innerHTML = txt;
        }
   </script>
</body>
</html>

Output:
In this output on clicking the button Microsoft will be replaced with Google.

These Methods does not end up here, rather there are even more methods to manipulate the string. We are just covering most important and useful one.


Regular Expression: -

When we search any data in the text, we can use search pattern to describe what we are searching for. It is a sequence of characters that forms a search pattern. It can be a single character or more. Also, it can be used for performing all types of text search and text replace operations.

Many a times regular expressions are used with String Methods and are search() and replace().

Regular Expression Modifiers: - Modifiers can be used to perform case-intensive matching.
i = for performing case-intensive matching.
g = for performing a global matching.
m = for performing multiline matching.

Regular Expression Patterns: - Brackets: These are used to find a range of characters
[abc]    Find any of the characters between the brackets
[0-9]    Find any of the digits between the brackets
(x|y)    Find any of the alternatives separated with |

Metacharacters: These characters are special meaning characters
\d    Find a digit
\s    Find a whitespace character
\b    Find a match at the beginning or at the end of a word
\uxxxx    Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers: Defines the Quantities
n+    Matches any string that contains at least one n
n*    Matches any string that contains zero or more occurrences of n
n?    Matches any string that contains zero or one occurrences of n

Syntax: -
var name = /pattern/modifiers;


Methods in Regular Expression: -

test() Method:-
test() method is a regular expression method. This method searches a string for a pattern and returns True or False, it depends on the result.
Ex:-
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<body>
  <p>Search for an "e" in the next paragraph:</p>
  <p id="p01">The best things in life are free! </p>
  <button onclick="myFunction()">Click On</button>
  <p id="demo"></p>
  <script>
  function myFunction() {
     var text = document.getElementById("p01").innerHTML;
     document.getElementById("demo").innerHTML = /e/.test(text);
 }
  </script>
</body>
</html>

Output:
In this output on clicking the button we get this output “true”.

exec() Method:-
This Method searches a string for a specified pattern, and returns the text found. If no match is found it returns the null.
Ex:-
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<body>
  <p>Search for an "e" in the next paragraph:</p>
  <p id="p01">The best things in life are free!</p>
  <button onclick="myFunction()">Click On</button>
  <p id="demo"></p>
  <script>
    function myFunction() {
      text = document.getElementById("p01").innerHTML;
      document.getElementById("demo").innerHTML = /e/.exec(text);
 }
  </script>
</body>
</html> 

Output:
In this output on clicking the button we will get the following answer ‘e’.

After going through the different methods of String Object and Regular Expression we can say these all these terms helps a lot in the programming a high-level UI and being a beginner, it is quite necessary to clear all the aspects carefully and then implement them in the script.

I hope this blog will be advantageous for you while learning JavaScript from any Web Design Training Institute.

No comments:

Post a Comment

Featured Post

ADMEC Multimedia Institute Scholarship Program

The ADMEC Multimedia Institute scholarship program aims to select and trained talented non working female, married woman and non married m...