JavaScript Underscore Library _.map function using RegX or _filter?

Given  the following code segments:
  lookupEvents={
    "/responsive/lead-form.":"event19",
    "checking-offer":"event29",
    "checking-offer-confirmation":"event32"
  };
...
 __.map(lookupEvents,function(value,key) {
            if(pathname.indexOf(key)!==-1) {returnValue.push(value);}
}

Open in new window


Is there a way to use a regX or other approach, possibly _filter, so both event29 and event32 are not set for URLs containing "checking-offer-confirmation"? I only want to set event32 for  "checking-offer-confirmation". I'm new to Underscore so not quiet sure how to handle this particular situation?

Thanks!
894359Asked:
Who is Participating?
 
Julian HansenCommented:
I think I understand what it is you are trying to do

You have a lookup table that looks like so
 lookupEvents={
    "/responsive/lead-form.":"event19",
    "checking-offer":"event29",
    "checking-offer-confirmation":"event32"
  };

Open in new window

The keys represent strings that will appear in the URL for the page.
The values are the items (events) you want to link to specific URL's that contain those strings.

Your problem is that checking-offer is a sub string of checking-offer-confirmation so when you look for a lookupEvent based on checking-offer you get two events returned.

The question is why do you want to use a regex - which will find partial matches just use an exact match.

First strip off the .html
var noext = windows.location.pathname.split(".")[0].toLowerCase();

Open in new window

Next iterate over your lookup events looking for a key that matches exactly the last N chars of the noext var above where N is the length of the key
// GET THE keys OF THE lookupEvents Object
var k = Object.keys(lookupEvents);

// ITERATE OVER THE KEYS LOOKING FOR A MATCH
for(var i = 0; i < k.length; k++) {

  // IF key IS SHORTER THAN noext THEN NO POINT IN GOING FURTHER
  if (noext.length < k[i].length) {

    // EXTRACT THE LAST N CHARS OF THE key USING THE LENGTH OF key
    var urlstr = noext.substr(-k[i].length);

    // CHECK IF KEY MATCHES AND RETURN value IF IT DOES
    if (k[i].toLowerCase() == urlstr) return lookupEvents[k[i]];
  }
}

Open in new window

0
 
Julian HansenCommented:
It is not clear from your description what you are trying to do

so both event29 and event32 are not set for URLs
What does this mean?

I only want to set event32 for  "checking-offer-confirmation"
Set what where?

You have not given us enough information to understand what it is you are trying to do.
0
 
894359Author Commented:
Sorry,  so  
pathname = location.pathname

Open in new window

so based on the path I'm adding events  associated to these paths to "returnValue[]" (events are for Adobe Analytics) . The issue is if I encounter page(s) that contains URLs with "-confirmation" on the end:

/dir1/checking-offer
/dir1/checking-offers
/dir2/checking-offers
/dir2/checking-offers.html
/dir1/checking-offer-confirmation
/dir1/checking-offers-confirmation
/dir2/checking-offers-confirmation
/dir2/checking-offers-confirmation.html

The way it currently is implemented, ALL the above will add "event29" to  "returnValue[]" because they all satisfy
if(pathname.indexOf(key)!==-1)

Open in new window

but I don't want that. If a URL contains the ""checking-offer-confirmation"" then I only want it to add "event32" to  "returnValue[]" . The way it is currently implemented, both "event29 and "event32" are added to "returnValue[]" because of:
if(pathname.indexOf(key)!==-1)

Open in new window

I do NOT want "event29" added for URLs that contain the "-confirmation" with "checking-offer".
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
Julian HansenCommented:
The way it currently is implemented, ALL the above will add "event29" to  "returnValue[]" because they all satisfy
Why? Where does event29 come from - you gave us 8 urls a loosely defined array (returnValue) and then suddenly out pops event29.

Assume that we don't know everything you know and that we have not seen your code or your specification. Then fill us in with all the facts we need to
a) Understand what is you are trying to do
b) Why you are having a problem with it
0
 
894359Author Commented:
Hi,
Sorry, trying to explain this best I can. The code takes in the current path name of the current page. For the following sample paths, the following "events" (events are the values associated in "lookupEvents"  which are Adobe Analytic events)  are currently returned :

/dir1/checking-offer ==> event29
/dir1/checking-offers ==> event29
/dir2/checking-offers ==> event29
/dir2/checking-offers.html ==> event29
/dir1/checking-offer-confirmation ==> event29 & event32
/dir1/checking-offers-confirmation ==> event29 & event32
/dir2/checking-offers-confirmation ==> event29 & event32
/dir2/checking-offers-confirmation.html ==> event29 & event32


The above results are due to
if(pathname.indexOf(key)!==-1) {returnValue.push(value);}

Open in new window

The issue is, I DO NOT want "event29" set for paths which contain "-confirmation" but currently they match "indexOf" for both conditions when compared to "checking-offer":"event29" My desired outcome would be the below:

/dir1/checking-offer ==> event29
/dir1/checking-offers ==> event29
/dir2/checking-offers ==> event29
/dir2/checking-offers.html ==> event29
/dir1/checking-offer-confirmation ==> event32
/dir1/checking-offers-confirmation ==> event32
/dir2/checking-offers-confirmation ==> event32
/dir2/checking-offers-confirmation.html ==> event32


Trying to figure out the best approach to accomplish this? New to Underscore library.
0
 
894359Author Commented:
I have a solution but I'm hoping there is a more elegant way to solve this?  I just added the check with the "specialCondition()" function check .
 if((pathname.indexOf(key)!==-1)&&(!specialCondition(key))) {returnValue.push(value);}

Open in new window

Test code below:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
 
	<title></title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta name="language" content="en">
	
<script  src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js" type="text/javascript" ></script>  
<script>

(function() {
  "use strict"; 
  var i,len,
      returnValue=[],  // This is the default event that fires on every page
	  //pathname = "checking-offer",
	  pathname = "checking-offer-confirmation",
  
  lookupEvents={
    "search-result":"event6",
    "/customer-service/branch":"event11",
    "checking-offer":"event29",
    "checking-offer-confirmation":"event32"
  };
  
  function specialCondition(key){

     switch (true) {  
        case ((pathname.indexOf("checking-offer") !=-1) && (pathname.indexOf(key) ==-1) && (key == "checking-offer-confirmation")):  
            return true; 
            break;  
        case ((pathname.indexOf("checking-offer-confirmation") !=-1) && (key == "checking-offer")):  
            return true; 
            break; 
        default:  
            return false;           
    }
  };
 
    _.map(lookupEvents,function(value,key) {
	   console.log("==> SpecialCondition for key: " + key + " & pathname: " + pathname + " ==> " + specialCondition(key));
      // Any matching key is added to the array
      if((pathname.indexOf(key)!==-1)&&(!specialCondition(key))) {returnValue.push(value);}
    });

  // Return back a comma-seperated list of events
  returnValue = returnValue.join(",");
  console.log(returnValue);
  //return returnValue.length>0?returnValue:0;
})();

</script>


</head>
<body>

</body></html>

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.