Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, August 4, 2022

How to Create a JavaScript Library/Framework?

 

Introduction

This article will teach you how to Create a Javascript Library or Framework.

Creating a JavaScript library

Library Name: Greeter

  • When given a first name, last name, and options language, it generates formal and informal greetings.
  • Supports English and Spanish languages.
  • Reusable library/framework.
  • Easy to type ‘G$()’ structure. -Support jQuery

Structure Safe code

HTML

<html>
  <head>      
  </head>
  <body>
      <script src="scripts/jquery-3.6.0.js"></script>
      <script src="scripts/greetr.js"></script>
      <script src="scripts/app.js"></script>
    </body>
</html>

Include jQuery first to enable the jQuery support.

greetr.js

We require a global variable window and jQuery. Set up an IIFE function by passing the windows and the jQuery function.

Now create an IIFE function to start with.


(function(global, $) {
}(window, jQuery));

Now, this is safe to use in any of the applications and ready to use.

The next step is to set up the greeter object and the alias similar to jQuery $. You can review code the code of the jQuery library understands the safe entry method to work with any library.


(function (global, $) {

  var Greetr = function (firstname, lastName, language) {
    return new Greetr.init(firstName, lastName, language);
  };

  // You can create your properties and function here
  Greetr.prototype = {};

  Greetr.init = function (firstName, lastName, language) {
    var self = this;
    self.firstName = firstName || "";
    self.lastName = lastName || "";
    self.language = language || "en";
  };

  Greetr.init.prototype = Greetr.prototype;

  //Set the alias
  global.Greetr = global.G$ = Greetr;
}(window, jQuery));


Adding Language support

Now we set up the language support for English and Spanish. Along with this

(function (global, $) {
  var Greetr = function (firstname, lastName, language) {
    return new Greetr.init(firstName, lastName, language);
  };

  var supportedLanguages = ["en", "es"];

  var greetings = {
    en: "Hello",
    es: "Hola",
  };

  var formalGreetings = {
    en: "Greetings",
    es: "Saludos",
  };

  var logMessages = {
    en: "Logged In",
    es: "iniciar la sesión",
  };

  // You can create your properties and function here
  Greetr.prototype = {
    fullName: function () {
      return this.firstName + " " + this.lastName;
    },
    validate: function () {
      if (supportedLanguages.indexOf(this.language) === -1) {
        throw "Invalid language";
      }
    },
    greeting: function () {
      return greetings[this.language] + " " + this.firstName + "!";
    },

    formalGreetings: function () {
      return formalGreetings[this.language] + " " + this.fullName() + "!";
    },
    greet: function (formal) {
      var msg;
      //if undefined or null, it will be coerced to 'false.'
      if (formal) {
        msg = this.formalGreetings();
      } else {
        msg = this.greeting();
      }

      if (console) {
        console.log(msg);
      }

      //'this' refers to the calling object at the execution time
      // makes the method chainable
      return this;
    },
    log: function () {
      if (console) {
        console.log(logMessages[this.language] + ": " + this.fullName());
      }
      return this;
    },
    setLanguage: function (lang) {
      this.language = lang;
      this.validate();
      return this;
    },
  };

  Greetr.init = function (firstName, lastName, language) {
    var self = this;
    self.firstName = firstName || "";
    self.lastName = lastName || "";
    self.language = language || "en";
  };

  Greetr.init.prototype = Greetr.prototype;

  //Set the alias
  global.Greetr = global.G$ = Greetr;
}(window, jQuery));


Calling the library in the application

var g = G$("Niranjan", "Singh");
//Chained behavior and call to display greetings
g.greet().greet(true);
//Change the language and then greet
g.greet().setLang('es').greet(true);


Adding jQuery support

We need to add jQuery support and provide the functionality to give the id to Greetr library for updating the element text.

Update the HTML page with the below text to enable/demonstrate the jQuery incorporation.


<html>

<head>
</head>

<body>
  <div id="logindiv">
    <select id="lang" div>
      <option value="en">English</option>
      <option value="es">Spanish</option>
    </select>
    <input type="button" name="login" id="login" value="Login">
  </div>
  <h1 id="greeting"></h1>
  <script src="scripts/jquery-3.6.0.js"></script>
  <script src="scripts/greetr.js"></script>
  <script src="scripts/app.js"></script>
</body>

</html>

It requires changes in the Greetr library also. So add a new method called HTMLGreeting with a selector parameter.


    HTMLGreeting: function (selector, formal) {
      if (!$) {
        throw "jQuery not loaded";
      }
      if (!selector) {
        throw "Missing jQuery selector ";
      }

      var msg;
      //if undefined or null, it will be coerced to 'false.'
      if (formal) {
        msg = this.formalGreetings();
      } else {
        msg = this.greeting();
      }

      $(selector).html(msg);

      return this;
    },

Below is the simple library/framework which we have developed. It could be referred to and used to create a library.

(function (global, $) {
  // 'new' an object
  var Greetr = function (firstName, lastName, language) {
    return new Greetr.init(firstName, lastName, language);
  };
  // hidden within the scope of the IIFE and never directly accessible
  var supportedLanguages = ["en", "es"];
  // informal greetings
  var greetings = {
    en: "Hello",
    es: "Hola",
  };
  // formal greetings
  var formalGreetings = {
    en: "Greetings",
    es: "Saludos",
  };
  // logger messages
  var logMessages = {
    en: "Logged In",
    es: "iniciar la sesión",
  };

  // You can create your properties and function here
  Greetr.prototype = {
    fullName: function () {
      return this.firstName + " " + this.lastName;
    },
    validate: function () {
      if (supportedLanguages.indexOf(this.language) === -1) {
        throw "Invalid language";
      }
    },
    greeting: function () {
      return greetings[this.language] + " " + this.firstName + "!";
    },

    formalGreetings: function () {
      return formalGreetings[this.language] + " " + this.fullName() + "!";
    },
    greet: function (formal) {
      var msg;
      //if undefined or null, it will be coerced to 'false.'
      if (formal) {
        msg = this.formalGreetings();
      } else {
        msg = this.greeting();
      }

      if (console) {
        console.log(msg);
      }

      //'this' refers to the calling object at the execution time
      // makes the method chainable
      return this;
    },
    log: function () {
      if (console) {
        console.log(logMessages[this.language] + ": " + this.fullName());
      }
      return this;
    },
    setLanguage: function (lang) {
      this.language = lang;
      this.validate();
      return this;
    },
    HTMLGreeting: function (selector, formal) {
      if (!$) {
        throw "jQuery not loaded";
      }
      if (!selector) {
        throw "Missing jQuery selector ";
      }

      var msg;
      //if undefined or null it will be coerced to 'false'
      if (formal) {
        msg = this.formalGreetings();
      } else {
        msg = this.greeting();
      }

      $(selector).html(msg);

      return this;
    },
  };
  // the actual object is created here, allowing us to 'new' an object without calling 'new'
  Greetr.init = function (firstName, lastName, language) {
    var self = this;
    self.firstName = firstName || "";
    self.lastName = lastName || "";
    self.language = language || "en";
    self.validate();
  };
  // trick borrowed from jQuery so we don't have to use the 'new' keyword
  Greetr.init.prototype = Greetr.prototype;

  //Set the alias, attach the Greetr to the global object and provide a shorthand '$G' for the ease our poor fingers
  global.Greetr = global.G$ = Greetr;
}(window, jQuery));

Conclusion

We have created a small library that supports the jQuery framework also. We can create an extensive library or framework by following the same pattern. The best way to learn this is by reviewing the existing open source libraries and frameworks, e.g., jQuery.

Tuesday, April 15, 2014

How does === means different than == in JavaScript?

These two operators do not mean the same and does different operation too.
== verifies if the compared values are equal
=== verifies if the variables that are compared have the same value and are the same type
JavaScript's standard equality operators (== and !=) check if two expressions are equal (or not equal). If the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison. Values are considered equal if they are identical strings, numerically equivalent numbers, the same object, identical Boolean values, or (if different types) they can be coerced into one of these situations.
JavaScript's identity (strict equality) operators (=== and !==) behave identically to the equality operators except no type conversion is done, and the types must be the same to be considered equal. Here are a few examples:
"3" == 3 // true
"3" === 3 // false
1 == true // true
1 === true // false
"1" == true // true
"1" === true // false

Code snippet:

<script type="text/javascript">
   var a = 5;
   var b = '5';
   var c = 5;
   if(a==b)
   {
      document.write('a and b have the same value');
   }

   if(a===b)
   {
      document.write('a and b have the same value and the same type');
   }
   if(a===c)
   {
      document.write('a and c have the same value and the same type');
   }
</script>


Thursday, November 10, 2011

How to get selected value of dropdownlist using JavaScript.

Form have a select element that looks like this:

<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>




Get Selected Value:




var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;


output:


strUser be 2.





Get Selected Item text:




var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;


output:


 strUser be test2

Wednesday, November 2, 2011

Creating Arrary in JavaScript

Create an Array

An array can be defined in three ways.
The following code creates an Array object called myCars:
Listing 1:
var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab";       // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";
Listing 2:

var myCars=new Array("Saab","Volvo","BMW"); // condensed array

Listing 3:

var myCars=["Saab","Volvo","BMW"]; // literal array

Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String.

Access an Array


You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.

The following code line:
document.write(myCars[0]);
will result in the following output:
Saab

Modify Values in an Array


To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";

Now, the following code line:
document.write(myCars[0]);


will result in the following output:
Opel

Opening a New Window With JavaScript

Use Window open() Method.
The open() method opens a new browser window.

Syntax

window.open(URL,name,specs,replace)

Parameter
URL

Optional. Specifies the URL of the page to open. If no URL is specified, a new window with about:blank is opened
name
Optional. Specifies the target attribute or the name of the window. The following values are supported:

  • _blank - URL is loaded into a new window. This is default
  • _parent - URL is loaded into the parent frame
  • _self - URL replaces the current page
  • _top - URL replaces any framesets that may be loaded
  • name - The name of the window ‘
<html>
<head>
<script type="text/javascript">
function open_win()
{
window.open(http://www.niranjankala.in”)
}
</script>
</head>
<body>
<input type=button value="Open Window" onclick="open_win()" />
</body>
</html>

Monday, October 17, 2011

Get Query String Using Javascript

The following javascript code snippet facilitates Javascript's built in regular expressions to retrieve value of the key. Optionally, you can specify a default value to return when key does not exist.

you can use this method in your aspx page as:

Tuesday, March 15, 2011

How to get Browser in JavaScript

The Navigator object contains information about the visitor's browser.


Browser Detection

Almost everything in this tutorial works on all JavaScript-enabled browsers. However, there are some things that
just don't work on certain browsers - especially on older browsers.

Sometimes it can be useful to detect the visitor's browser, and then serve the appropriate information.

The Navigator object contains information about the visitor's browser name, version, and more.

NoteNote: There is no public standard that applies to the navigator object, but all major browsers support it.


The Navigator Object

The Navigator object contains all information about the visitor's browser:

Example

/* <div id="example"></div>

<script type="text/javascript">

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";

document.getElementById("example").innerHTML=txt;

</script>

*/

The output will be

Browser CodeName: Mozilla

Browser Name: Netscape

Browser Version: 5.0 (Windows; en-US)

Cookies Enabled: true

Platform: Win32

User-agent header: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13)
Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)

 

JavaScript RegExp for Validation

A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text.

Syntax

var patt=new RegExp(pattern,modifiers);

or more simply:

var patt=/pattern/modifiers;
  • pattern specifies the pattern of an expression
  • modifiers specify if a search should be global, case-sensitive, etc.

Modifiers

Modifiers are used to perform case-insensitive and global searches:
Modifier
Description
Perform case-insensitive matching
Perform a global match (find all matches rather than stopping after the first match)
m
Perform multiline matching

Brackets

Brackets are used to find a range of characters:
Expression
Description
Find any character between the brackets
Find any character not between the brackets
[0-9]
Find any digit from 0 to 9
[A-Z]
Find any character from uppercase A to uppercase Z
[a-z]
Find any character from lowercase a to lowercase z
[A-z]
Find any character from uppercase A to lowercase z
[adgk]
Find any character in the given set
[^adgk]
Find any character outside the given set
(red|blue|green)
Find any of the alternatives specified

Metacharacters

Metacharacters are characters with a special meaning:
Metacharacter
Description
Find a single character, except newline or line terminator
Find a word character
Find a non-word character
Find a digit
Find a non-digit character
Find a whitespace character
Find a non-whitespace character
Find a match at the beginning/end of a word
Find a match not at the beginning/end of a word
\0
Find a NUL character
Find a new line character
\f
Find a form feed character
\r
Find a carriage return character
\t
Find a tab character
\v
Find a vertical tab character
Find the character specified by an octal number xxx
Find the character specified by a hexadecimal number dd
Find the Unicode character specified by a hexadecimal number xxxx

Quantifiers

Quantifier
Description
Matches any string that contains at least one n
Matches any string that contains zero or more occurrences of n
Matches any string that contains zero or one occurrences of n
Matches any string that contains a sequence of X n's
Matches any string that contains a sequence of X to Y n's
Matches any string that contains a sequence of at least X n's
Matches any string with n at the end of it
Matches any string with n at the beginning of it
Matches any string that is followed by a specific string n
Matches any string that is not followed by a specific string n

RegExp Object Properties

Property
Description
Specifies if the "g" modifier is set
Specifies if the "i" modifier is set
The index at which to start the next match
Specifies if the "m" modifier is set
The text of the RegExp pattern

RegExp Object Methods

Method
Description
Compiles a regular expression
Tests for a match in a string. Returns the first match
Tests for a match in a string. Returns true or false

test()

The test() method searches a string for a specified value, and returns true or false, depending on the result.
The following example searches a string for the character "e":

Example

var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));

Since there is an "e" in the string, the output of the code above will be:
true

exec()

The exec() method searches a string for a specified value, and returns the text of the found value. If no match is found,
it returns null.

The following example searches a string for the character "e":

Example 1

var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));

Since there is an "e" in the string, the output of the code above will be:
e

You can read this from www.w3schools.com.

Array in Javascript

The Array object is used to store multiple values in a single variable.
An array can hold all your variable values under a single name. And you can access the values by referring to the
array name.
Each element in the array has its own ID so that it can be easily accessed.


Create an Array
An array can be defined in three ways.
The following code creates an Array object called myCars:
1:
var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab";       // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";
2:
var myCars=new Array("Saab","Volvo","BMW"); // condensed array
3:
var myCars=["Saab","Volvo","BMW"]; // literal array
Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean,
instead of String.


Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index number. The index
number starts at 0.
The following code line:
document.write(myCars[0]);
will result in the following output:
Saab



Modify Values in an Array
To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel


*/
<html>
<body>

<script type="text/javascript">
var i;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (i=0;i<mycars.length;i++)
{
document.write(mycars[i] + "<br />");
}
</script>

</body>
</html>

// concat two array

var parents = ["Jani", "Tove"];
var children = ["Cecilie", "Lone"];
var family = parents.concat(children);
document.write(family);


*/



campare two dates in Javascript

The Date object is also used to compare two dates.

The following example compares today's date with the 14th January 2011:

/* var myDate=new Date();
myDate.setFullYear(2011,0,14);
var today = new Date();

if (myDate>today)
  {
  alert("Today is before 14th January 2011");
  }
else
  {
  alert("Today is after 14th January 2011");
  }

*/

Creating a Digital Clock in Javascript

/*

<html>

<head>

<script type="text/javascript">

function startTime()

{

var today=new Date();

var h=today.getHours();

var m=today.getMinutes();

var s=today.getSeconds();

// add a zero in front of numbers<10

m=checkTime(m);

s=checkTime(s);

document.getElementById('txt').innerHTML=h+":"+m+":"+s;

t=setTimeout('startTime()',500);

 

}

 

function checkTime(i)

{

if (i<10)

  {

  i="0" + i;

  }

return i;

}

</script>

</head>

 

<body onload="startTime()">

<div id="txt"></div>

</body>

</html>

*/

Monday, March 14, 2011

validation using javascript



/*
function validate()
{
// for check that text box is fill or empty.
     if (document.getElementById("<%=txtName.ClientID%>").value=="")

     {
                alert("Name Feild can not be blank");
                document.getElementById("<%=txtName.ClientID %>").focus();
                return false;
     }
     if(document.getElementById("<%=txtEmail.ClientID %>").value=="")
     {
                alert("Email can not be blank");
               document.getElementById("<%=txtEmail.ClientID%>").focus();
               return false;
     }
// check that email address is valid or not.
    var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
    var emailid=document.getElementById("<%=txtEmail.ClientID%>").value;
   var matchArray = emailid.match(emailPat);
    if (matchArray == null)
       {
                  alert("Your email address seems incorrect. Please try again.");
                  document.getElementById("<%=txtEmail.ClientID%>").focus();
                  return false;
       }
     if(document.getElementById("<%=txtCourse.ClientID%>").value=="")
     {
                alert("Cousrse field can not be blank");
               document.getElementById("<%=txtCourse.ClientID%>").focus();
               return false;
     }

     return true;
 }
</script> */

Saturday, March 12, 2011

regular expression in javascript

 
 

 

A regular expression object is an instance of the RegExp object. Each regular expression object consists of a
pattern that is used to locate matches within a string. Patterns for a regular expression can be simple strings or
significantly more powerful expressions that use a notation that is essentially a language unto itself. The
implementation of regular expressions in JavaScript 1.2 is very similar to the way they are implemented in Perl.
You can read more about these concepts in books covering JavaScript 1.2 or later.

 

To create a regular expression object, surround the pattern with forward slashes, and assign the whole
expression to a variable. For example, the following statement creates a regular expression with a pattern that
is a simple word:

var re = /greet/;
 

The re variable can then be used as a parameter in a variety of methods that search for the pattern within some
string (you may also use an expression directly as a method parameter, rather than assigning it to a variable).

 

Regular expression notation also consists of a number of metacharacters that stand in for sometimes complex
ideas, such as the boundary on either side of a word, any numeral, or one or more characters. For example,
to search for the pattern of characters shown above but only when the pattern is a word (and not part of a
word such as greetings), the regular expression notation uses the metacharacters to indicate that the pattern
includes word boundaries on both sides of the pattern:

var re = /\bgreet\b/;
 

The following table shows a summary of the regular expression notation used in JavaScript 1.2.

 

When you create a regular expression, you may optionally wire the expression to work globally (as you
probably do if the regular expression is doing a search-and-replace operation with a method, and your goal
is a "replace all" result) and to ignore case in its matches. The modifiers that turn on these switches are the
letters g and i. They may be used by themselves or together as gi.

 

Once you have established a pattern with the regular expression notation, all the action takes place in the
regular expression object methods and the String object methods that accept regular expression parameters.

 
Character Matches Example
\b Word boundary /\bto/ matches "tomorrow"/to\b/ matches "Soweto"
\B Word nonboundary /\Bto/ matches "stool" and "Soweto"/to\B/ matches "stool" and "tomorrow"
\d Numeral 0 through 9 /\d\d/ matches "42"
\D Nonnumeral /\D\D/ matches "to"
\s Single whitespace /under\sdog/ matches "under dog"
\S Single nonwhitespace /under\Sdog/ matches "under-dog"
\w Letter, numeral, or underscore /1\w/ matches "1A"
\W Not a letter, numeral, or underscore /1\W/ matches "1%"
. Any character except a newline /../ matches "Z3"
[...] Any one of the character set in brackets /J[aeiou]y/ matches "Joy"
[^...] Negated character set /J[^eiou]y/ matches "Jay"
* Zero or more times /\d*/ matches "", "5", or "444"
? Zero or one time /\d?/ matches "" or "5"
+ One or more times /\d+/ matches "5" or "444"
{n} Exactly n times /\d{2}/ matches "55"
{n,} n or more times /\d{2,}/ matches "555"
{n,m} At least n, at most m times /\d{2,4}/ matches "5555"
^ At beginning of a string or line /^Sally/ matches "Sally says..."
$ At end of a string or line /Sally.$/ matches "Hi, Sally."
 
Properties
 
constructor global ignoreCase lastIndex source
 
Methods
 
compile( ) exec( ) test( )
 
Creating a regular expression Object
 
var regExpressionObj = /pattern/ [g | i | gi]; var regExpressionObj = new RegExp(["pattern", ["g" | "i" | "gi"]]);
constructor NN 4 IE 4 ECMA 3 

Read/Write 

See this property for the Array object.

global, ignoreCase

 

 

Returns Boolean true if the regular expression object instance had the g or i modifiers (respectively) set when
it was created. If a regular expression object has both modifiers set (gi), you must still test for each property
individually.

 
Example
 
if (myRE.global && myRE.ignoreCase) {     ... }
 
Value

Boolean value: true | false.

lastIndex

 

This is the zero-based index value of the character within the string where the next search for the pattern begins.
In a new search, the value is zero. You can also set the value manually if you wish to start at a different location
or skip some characters.

 
Example
 
myRE.lastIndex = 30;
 
Value

Integer.

source
 

 

Returns a string version of the characters used to create the regular expression. The value does not include the
forward slash delimiters that surround the expression.

 
Example
 
var myREasString = myRE.source;
 
Value

String.

compile( )

compile("pattern"[, "g" | "i" | "gi"])

 

Compiles a regular expression pattern into a genuine regular expression object. This method is used primarily
to recompile a regular expression with a pattern that may change during the execution of a script.

 
Parameters
 
  • Any regular expression pattern as a quoted string. Modifiers for global, ignore case, or both must be
    supplied as a separate quoted parameter.
 
Returned Value

Reference to a regular expression instance.

exec( )

exec(string)

 

Performs a search through the string passed as a parameter for the current regular expression pattern. A typical
sequence follows the format:

var myRE = /somePattern/; var resultArray = myRE.exec("someString");
 

Properties of both the static RegExp and regular expression instance (myRE in the example) objects are updated
with information about the results of the search. In addition, the exec( ) method returns an array of data, much
of it similar to RegExp object properties. The returned array includes the following properties:

index

Zero-based index of starting character in the string that matches the pattern

input

The original string being searched

[0]

String of the characters matching the pattern

[1]...[n]

Strings of the results of the parenthesized component matches

 

You can stow away the results of the exec( ) method in a variable, whereas the RegExp property values change
with the next regular expression operation. If the regular expression is set for global searching, a subsequent call
to myRE.exec("someString") continues the search from the position of the previous match.

 

If no match is found for a given call to exec( ), it returns null.

 
Parameters
 
  • The string to be searched.
 
Returned Value

An array of match information if successful; null if there is no match.

test( )

test(string)

 

Returns Boolean true if there is a match of the regular expression anywhere in the string passed as a parameter,
false if not. No additional information is available about the results of the search. This is the fastest way to find out
if a string contains a match for a pattern.

 
Parameters
 
  • The string to be searched.
 
Returned Value

Boolean value: true | false.