Solved

Trying to impliment a like function in JavaScript.

Posted on 2016-10-11
10
102 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
[X]
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
  • 5
  • 4
10 Comments
 
LVL 58

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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
LVL 58

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 58

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 58

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 58

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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.

Question has a verified solution.

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

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…
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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)
Suggested Courses

623 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