简体   繁体   English

如何区分javascript对象中的url和字符串

[英]How to differentiate between a url and string in javascript object

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.我有一个包含media_id和某种链接的对象,该链接导航到我的音频屏幕页面,第二个media_id包含一个将转到视频屏幕页面的字符串。 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,



          });
    }}>

一个快速而简单的解决方案是检查您的字符串是否包含“https:” https://www.w3schools.com/jsref/jsref_search.asp

You can use startsWith , which is a method inside any String prototype's.您可以使用startsWith ,它是任何 String 原型中的方法。

Try using this on your check:尝试在您的支票上使用它:

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

Check if the media_id begins with https using startsWith .使用startsWith检查media_id是否以https开头。 If it begin with https it is an url else id string .如果它以https开头,则它是一个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); } });

You can check for substring as,您可以检查子字符串,

media_id.includes("https://")

or without SSL或不使用 SSL

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

Now if it either starts with or has another url in it.现在,如果它以另一个url开头或其中包含另一个url 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);
}

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!您可以尝试解析它,如果解析失败,您就知道它不是 URL! With the advantage of working for any kind of protocol, not just HTTP.具有适用于任何类型协议的优势,而不仅仅是 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,
          });
    }}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM