Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove this JavaScript null error?

Tags:

javascript

I'm using the following to create an if statement based on the last word of the url after the slash:

  // Sticky

  var match = location.search.match(/(\w+)$/)[0];

  if (match === 'complete') {
    $('p:has(audio)').addClass('sticky-child');
    $('p:has(audio)').appendTo('.lesson_lang_switch');
  }

The problem is, the front page doesn't have any word at the end of the URL (After the slash):

www.example.com/

So I get this error:

Uncaught TypeError: Cannot read property '0' of null 

How can I do it so that the error doesn't appear?

like image 800
alexchenco Avatar asked Dec 02 '22 17:12

alexchenco


1 Answers

You could add a conditional check. i.e.

var match = (location.search.match(/(\w+)$/)) 
    ? location.search.match(/(\w+)$/)[0] 
    : "";

 if (match === 'complete') { // match will be "" if the above is false
    $('p:has(audio)').addClass('sticky-child');
    $('p:has(audio)').appendTo('.lesson_lang_switch');
 }
like image 102
atmd Avatar answered Dec 05 '22 06:12

atmd