0

js判断字符串是否是Html或者url及html反转方案

 1 year ago
source link: https://www.haorooms.com/post/js_html_url_trans
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文主要是技术积累文章,主要记录收集几个js判断是否是html,及判断url正则及html转义方案。

js判断字符串是否是html

function isHTML(str) {
  var a = document.createElement('div');
  a.innerHTML = str;

  for (var c = a.childNodes, i = c.length; i--; ) {
    if (c[i].nodeType == 1) return true;
  }

  return false;
}
function isHtml(input) {
    return /<[a-z]+\d?(\s+[\w-]+=("[^"]*"|'[^']*'))*\s*\/?>|?\w+;/i.test(input);
}
const isHTML = (text) => {
  try {
    const fragment = new DOMParser().parseFromString(text,"text/html");
    return fragment.body.children.length>0
  } catch(error) { ; }  
  return false;
}

js判断字符串是否是url (仅http/https)

要求不高的化,可以简单判断一下https和http就可以了

/^(http:|https:)/ig

严格判断可以用如下:

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);
}

通过new Url的方案的化,兼容性不好,ie11不支持,可以用如下:

function isValidHttpUrl(string) {
  let url;

  try {
    url = new URL(string);
  } catch (_) {
    return false;
  }

  return url.protocol === 'http:' || url.protocol === 'https:';
}

html转义方案

后端对提交的数据进行了一些转义操作,比如

 <p><b>123&456</b></p>

这样的,会被转义成

 <p><b>123&456</b></p>

然后前端请求数据时,这些数据需要反转义一下。

通过如下方式

export function HTMLDecode(text) {
  var temp = document.createElement('div');
  temp.innerHTML = text;
  var output = temp.innerText || temp.textContent;
  temp = null;
  return output;
}
//HTML转义
function HTMLEncode(html) {
  var temp = document.createElement('div');
  temp.textContent != null
    ? (temp.textContent = html)
    : (temp.innerText = html);
  var output = temp.innerHTML;
  temp = null;
  return output;
}

var tagText = '<p><b>123&456</b></p>';
console.log(HTMLEncode(tagText)); //<p><b>123&456</b></p>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK