公共方法记录

24 阅读1分钟

``

export const getDeviceType = (userAgent) => {
  return /phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone|webOS|android/i.test(
    userAgent
  );
};

export const isJSON = (str) => {
  if (typeof str === 'string') {
    try {
      const obj = JSON.parse(str);
      if (typeof obj === 'object' && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      // eslint-disable-next-line
      console.log('error:' + str + '!!!' + e);
      return false;
    }
  }
  // eslint-disable-next-line
  console.log('It is not a string!');
};

export const isWeixin = (userAgent) => {
  const ua = userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) + '' === 'micromessenger') {
    return true;
  } else {
    return false;
  }
};

export const downloadFile = ({ url, fileName }) => {
  return new Promise((resolve) => {
    const a = document.createElement('a');
    a.setAttribute('download', fileName.substring(0, fileName.lastIndexOf('.')));
    a.setAttribute('href', url);
    document.documentElement.appendChild(a);
    a.target = '_black';
    a.click();
    document.documentElement.removeChild(a);
    resolve({
      code: 200,
      message: '下载完成'
    });
  });
};

export const materialsNamesText = (materialsNames) => {
  // eslint-disable-next-line no-console
  // console.log('[materialsNames]', materialsNames);
  return materialsNames.replace(
    /<file id="([0-9a-zA-Z|-]+)">([^<]+)<\/file>/g,
    function reg($0, $1, $2) {
      // eslint-disable-next-line no-console
      // console.log('[$1]', $1);
      // eslint-disable-next-line no-console
      // console.log('[$2]', $2);
      return `<a href="/download/${$1}">${$2}</a>`;
    }
  );
};