Search a pattern using Regular Expression


Search a pattern in strings using regular expression method match. Lets see methods startswith and endswith pattern searching of the given string.

Example : startsWith – check whether if a string is starts with the specified prefix.

function startsWith()
{
var input = prompt(“Enter search value : “);
var regex = “^”+input;
var arr = new Array(“Ajax Books”, “Javascript”, “Java”, “JSP & Servlet”, “MySQL”, “Regular Expression”);
for(i=0; i<arr.length; i++){
str=arr[i];
if( str.match(regex) == input){
alert(“Matching string is : ” +str);
}
}
}

Regular Expression : ^ – matches the beginning of the input string
For instance, input is “Regular”
output : alert should be Matching string is Regular Expression

Example : endsWith – check whether if a string is ends with the specified suffix.

function endsWith()
{
var input = prompt(“Enter search value : “);
var regex = input+”$”;
var arr = new Array(“Ajax Books”, “Javascript”, “Java”, “JSP & Servlet”, “MySQL”, “Regular Expression”);
for(i=0; i<arr.length; i++){
str=arr[i];
if( str.match(regex) == input){
alert(“Matching string is : ” +str);
}
}
}

Regular Expression : $ – matches end of the input string
For instance, input is “Books”
output : alert should be Matching string is Ajax Books
Are you new to regular expressions, read here https://manikandanmv.wordpress.com/2008/11/04/using-regular-expressions-in-javascript/

Advertisements

Tags: , , , , , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: