Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Trying to impliment a like function in JavaScript.

Posted on 2016-10-11
10
83 Views
Last Modified: 2016-10-13
Trying to build my own JavaScript function, but I need some help with the advanced code snip that I found.
I keep getting errors that state the "default value for object cannot be found ..." or " ... the method 'test' is not a member of ..."
or " ... the method 'exec' is not a member of ..."

//String.prototype.like = function(search) {    // this line produces an error about a sealed class ...

bRet = Like("TestString", "S");

function Like(string, MySearch) {
	if (typeof MySearch !== 'string' || this === null) {return false; }
	// Remove special chars 
	MySearch = MySearch.replace(new RegExp("([\\.\\\\\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:\\-])", "g"), "\\$1"); 
	// Replace % and _ with equivalent regex 
	MySearch = MySearch.replace(/%/g, '.*').replace(/_/g, '.'); 
	
	next.setProperty("MySearch", MySearch);
	
	// Check matches 
	return RegExp('^' + MySearch + '$', 'gi').test(this); 
	
	//return string.test(MySearch);
	//return MySearch.test(string);
	
}

Open in new window

0
Comment
Question by:sidwelle
  • 5
  • 4
10 Comments
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 41839847
What is it you are wanting the function to do?
0
 
LVL 27

Expert Comment

by:BigRat
ID: 41839859
Why has the function two parameters, yet only the second one is referenced?

Why do you test against "this"? I consider "this" to be dangerous since it's value can be context dependent.

I would also change the name of the first parameter from "string" to something like "Data". It's less confusing.

And finally what is "next"?
0
 

Author Comment

by:sidwelle
ID: 41839972
next is an object for anther part of the app. sorry that should have been removed.

The purpose is to compare filenames against a pattern much like command line.

bRet = Like("ProjectFile.doc", "*File.doc");    //would return true
0
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 55

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41840142
What are the potential inputs?
Usual ones are  * and ? do you want to support more

Seems to me you want to turn *File.doc into .*File\.doc

Something like this maybe
function Like(src, pattern) 
{
	var np = pattern.replace(/\*/g,'\.\*');
	var np = np.replace(/\?/g,'.');
	return src.match(new RegExp(np));

}

Open in new window

0
 

Author Comment

by:sidwelle
ID: 41840501
Ok, that helps. Here is what I have so far and it seems to work.
Can you see any place that it might break ?

Why do you need the "new RegExp(np)" at all, why not just:
var ax = src.toLowerCase().match(np);  //??

function IsLike(src, pattern)
{
	var np = pattern.toLowerCase();
	np = np.replace(/\*/g,'\.\*');
	np = np.replace(/\?/g, '.');
	np = np.replace(/\#/g, '[0-9]');
	//return src.match(new RegExp(np));
	
	var ax = src.toLowerCase().match(new RegExp(np));
	
	try 
	{
		if (ax[0] != null)
			{return true;}
		else 
			{return false;} 
			
	} catch(e)
	{
		return false;
	}	

	// if somehow we got here, just return false !
	return false;		
}

Open in new window

0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 41840558
You can use np directly - I have a habit of using RegExp as much of the time I am building dynamic regular expressions.

Breaking it - the best solution is to build up a set of test cases - both positives and negatives - run them through and check that each one behaves according to requirement.
0
 

Author Closing Comment

by:sidwelle
ID: 41841073
Works, thanks for the help.

I will post back if I have any more issues.
0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 41841388
You are welcome.
0
 

Author Comment

by:sidwelle
ID: 41842212
Playing with it more, why not just use the "search" method ?

Not really even sure what the "RegExp()" cmd does, inless it resolves any search parameters ?

function IsLike(src, pattern)
{
	var np = pattern.toLowerCase();
	np = np.replace(/\*/g,'\.\*');
	np = np.replace(/\?/g, '.');
	np = np.replace(/\#/g, '[0-9]');
	//return src.match(new RegExp(np));
	
	//var ax = src.toLowerCase().match(new RegExp(np));
      var ax = src.toLowerCase().search(new RegExp(np));

	try 
	{
		//if (ax[0] != null)
                if (ax > -1)
			{return true;}
		else 
			{return false;} 
			
	} catch(e)
	{
		return false;
	}	

	// if somehow we got here, just return false !
	return false;		
}

Open in new window

0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 41842267
RegExp creates a new Regular Expression object.
Consider this sample TeaBagFile.doc
And you want to search for T*File.doc
Search won't help you there because it loos for an exact match.
You want to change the above into
T.*File\.doc
And then run that through a regular expression checker.

Which raises the point that you will need to run a replace to fix the special characters that need to be escaped like '.'
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Asp in script 6 36
iframe - style elements within an iframe 7 36
Filktering Alphabetically 8 29
JQuery Syntax... 4 33
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question