1

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?

1 Answer 1

1

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]; 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.