0

I am setting substrings

var hash = document.location.hash;

// create an object to act like a dictionary to store each value indexed by its key
var partDic = {};

// remove the leading "#" and split into parts
var parts = hash.substring(1).split('&');

// If you just want the first value, whatever it is, use this.
// But be aware it's a URL so can be set to anything in any order, so this makes little sense
// var string = parts[0].split('=')[1];

// build the dictionary from each part
$.each(parts, function(i, v) {
// do the "=" split now
var arr = v.split("=");

// decode to turn "%5B" back into "[" etc
var key = decodeURIComponent(arr[0]);
var value = decodeURIComponent(arr[1]);

// store in our "dictionary" object
partDic[key] = value;
});

setTimeout( function() {
    var ag = partDic["comboFilters[Agencies]"].substring(1);
    $('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
    var cl = partDic["comboFilters[Clients]"].substring(1);
    $('.Client .dropdown-toggle').html(cl).append(' <span class="caret"></span>');
    var yr = partDic["comboFilters[Years]"].substring(1).slice(1);
    $('.Year .dropdown-toggle').html(yr).append(' <span class="caret"></span>');
}, 1000);

But if there is not a substring, I am getting:

Uncaught TypeError: Cannot read property 'substring' of undefined

I am guessing I need a simple if/else but I am not sure how to in this case

rob.m
  • 9,843
  • 19
  • 73
  • 162

3 Answers3

0

USE

 var cl = (partDic["comboFilters[Clients]"] && partDic["comboFilters[Clients]"].length>0)?partDic["comboFilters[Clients]"].substring(1):'';
Dev
  • 6,628
  • 2
  • 25
  • 34
  • what if `partDic["comboFilters[Clients]"]` is null, will it be any exception thrown? – Bhushan Kawadkar Jan 15 '15 at 09:45
  • what if I have .slice(1) after substring, like .substring(1).slice(1) ? – rob.m Jan 15 '15 at 09:47
  • you again have to check that.you can use as many ternary operators as you need just use braces to separate parts – Dev Jan 15 '15 at 09:48
  • no luck, if it has no substring i get empty text. Basically what if I have a simple url www.example.com so we have no substrings at all? However It works fine as it was with my code if substrings are there like www..ex.com/#comboFilters%5BAgencies%5D=.TBWA&comboFilters%5BClients%5D=.Vodafone&comboFilters%5BYears%5D=.y2013 – rob.m Jan 15 '15 at 09:57
0

Use Condition like:

If(partDic["comboFilters[Agencies]"].length>0)
{
----your code---
}
else{}
0

Thanks to this answer, I got this as a solution:

if("comboFilters[Agencies]" in partDic) {
   var ag = partDic["comboFilters[Agencies]"].substring(1);
   $('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
}
Community
  • 1
  • 1
rob.m
  • 9,843
  • 19
  • 73
  • 162