Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why regex is giving me Uncaught TypeError: Cannot read properties of null (reading '1')?

I have this form

<form onsubmit="return false">
  <p>Enter the URL:</p><input id="ur" type="text" name="url">
  <button type="submit" class="button secondary" id="myBtn" onclick="myFunction();" value="Load">Load</button>
</form>

<p id="demo"></p>

I have this function

function myFunction(){   
  var inputString = document.getElementById("ur").value;
  var result = inputString.match(/http:\/\/(?:.*\.|.*)imdb.com\/(?:t|T)itle(?:\?|\/)(..\d+)/i);
  document.getElementById("demo").innerHTML = result[1];
}

Result is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Uncaught TypeError: Cannot read properties of null (reading '1')

I am not sure where I am making mistake in my function.

I am expecting to get

tt8760708

from

https://www.imdb.com/title/tt8760708

on click on button as you can see.

>Solution :

Change your function to this:

function myFunction(){   
  var inputString = document.getElementById("ur").value;
  var result = inputString.match(/^(?:https?:\/\/)?(?:www\.|m\.)?(?:imdb.com\/title\/)?(tt[0-9]+)/i);
  document.getElementById("demo").innerHTML = result? result[1]: '';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading