Solved

Trying to impliment a like function in JavaScript.

Posted on 2016-10-11
10
62 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 51

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
 
LVL 51

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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 51

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 51

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 51

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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…
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
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…

757 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now