js 常用方法

1、url参数转对象

/**
 * @param {string} url
 * @returns {Object}
 */
// 方法一:
function param2Obj(url) {
  const search = decodeURIComponent(url.split("?")[1]).replace(/+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}
// 使用
let obj = param2Obj(window.location.href);
console.log(obj);  // {token: "aa", pass: "1321daf413", zhanghao: "you"}

// 方法二:
/**
 * @param {string} url
 * @returns {Object}
 */
function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

2、json对象转url参数

/**
 * @param {Object} json
 * @returns {Array}
 */
function param(json) {
  if (!json) return "";
  return cleanArray(
    Object.keys(json).map((key) => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
}
// 使用
let a = { name: "aaa", pass: "123456" };
console.log(param(a));  // name=aaa&pass=123456

3、生成唯一字符串

function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}

4、html转text

function html2Text(val) {
  const div = document.createElement("div");
  div.innerHTML = val;
  return div.textContent || div.innerText;
}
// 使用
let p = `<p>你好呀呵呵呵 <span>aaaa</span></p>`;
console.log(html2Text(p));  // 你好呀呵呵呵 aaaa

5、判断元素是否含有某个类

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp("(\s|^)" + cls + "(\s|$)"));
}

6、给元素添加某个类

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

7、删除元素的某个类

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\s|^)" + cls + "(\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

8、获取字符串的字节长度

/**
 * @param {string} input value
 * @returns {number} output value
 */
function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}
原文地址:https://www.cnblogs.com/aze999/p/14987432.html