How to differentiate between a url and string in javascript object

Viewed 327

I have an object which contains media_id with some sort of link which is navigating to my Audio screen page and a second media_id contains a string which is going to video screen page. How can I tell between them to navigate send them to their specific pages. My code is below:

API:

{
        "id": 602,
        "title": "Reflections on Africa",
     "media_id": "https://cdn.islamicmedia.com.au/site/2020/03/2019-11-18-Reflections-on-Africa-by-
    },
{
    "id": 595,
    "title": "Reflections on Africa ",
   ahmed-bassal/",
    "media_id": "8ZVwBwq2cTs",


},`

My code (will provide more code if u want). I know I'm doing something wrong so pls correct me

<TouchableOpacity
    onPress={() => {
      item.media_id === String
        ? this.props.navigation.navigate('Video', {
            id: item.id,
          })
        : this.props.navigation.navigate('Audio', {
            id: item.id,



          });
    }}>
6 Answers

You can check for substring as,

media_id.includes("https://")

or without SSL

media_id.includes("https://" | "http://")

Now if it either starts with or has another url in it. You can differenciate.

The best way is regex

function validURL(str) {
  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
    '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
  return !!pattern.test(str);
}

You can use startsWith, which is a method inside any String prototype's.

Try using this on your check:

item["media_id"].startsWith("https://")

Check if the media_id begins with https using startsWith. If it begin with https it is an url else id string.

const input = [{
    "id": 602,
    "title": "Reflections on Africa by Brother Ahmed Bassal",
    "media_id": "https://cdn.islamicmedia.com.au/site/2020/03/2019-11-18-Reflections-on-Africa-by-"
  },
  {
    "id": 595,
    "title": "Reflections on Africa by Brother Ahmed Bassal",
    "media_id": "8ZVwBwq2cTs",
  }
];

input.forEach(({
  media_id
}) => {
  if (media_id.startsWith('https')) {
    console.log('URL', media_id);
  } else {
    console.log('ID', media_id);
  }
});

Try with a regex

//arr is your API result
{this.state.arr.map((item, index) => {
  return (
    <TouchableOpacity
       onPress={() => {
         item.media_id.match("^https")
        ? this.props.navigation.navigate('Video', {
            id: item.id,
          })
        : this.props.navigation.navigate('Audio', {
            id: item.id,
          });
    />
  );
)}

You can try parsing it, and if it fails, you know it's not an URL! With the advantage of working for any kind of protocol, not just HTTP.

function isUrl(thing) {
    try {
        new URL(thing);
        return true;
    } catch (_) {
        return false;
    }
}

Then you can use it simply:

<TouchableOpacity
    onPress={() => {
      isUrl(item.media_id)
        ? this.props.navigation.navigate('Audio', {
            id: item.id,
          })
        : this.props.navigation.navigate('Video', {
            id: item.id,
          });
    }}>
Related