deverasha
deverasha

Reputation: 75

Cannot read property 'split' of undefined jquery

Hello guys I'm trying to create a function to get the full link if it has #mystring is exists for example

www.mydomian.com/#mystring&.........

but when I split it shows me errors

Uncaught TypeError: can't access property "split", data[1] is undefined

   function my_function() {

      var link = window.location +''; // get website link as string www.mydomain.com

      var data = link.split("#");  // start link after # for example www.mydomain.com/#mystring&anotherstring=hello
      
      var widget_type = data[1].split("&")[0]; // to get "mystring" 


         if(widget_type == 'mystring') { // check if "mystring" in the link exists
           var link = window.location.hash.substr(1); // get full link
            console.log(link)
         }
   
      
   }
   my_function();

so how can i check if "#mystring" is exits in my link before do it and fix split error?

Upvotes: 1

Views: 348

Answers (1)

Mina
Mina

Reputation: 17119

If the link doesn't contain #, the data array after splitting will contain only one item which is the link, So you need to check if there is a second item in the data by optional chaining after data[1]

var widget_type = data[1]?.split("&")[0]

Or you can use if condition.

const path = data[1]

var widget_type = '';

if (path) {
   widget_type = path.split("&")[0]; 
}

Upvotes: 1

Related Questions