# 字符串相关

验证数据类型,处理字符串相关功能

# 校验数据类型


export const typeOf = function(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}

typeOf('树哥')  // string
typeOf([])  // array
typeOf(new Date())  // date
typeOf(null) // null
typeOf(true) // boolean
typeOf(() => { }) // function

检查值是否属于特定类型


const is = (type, val) => ![, null].includes(val) && val.constructor === type;

is(Array, [1]); // true
is(ArrayBuffer, new ArrayBuffer()); // true
is(Map, new Map()); // true
is(RegExp, /./g); // true
is(Set, new Set()); // true
is(WeakMap, new WeakMap()); // true
is(WeakSet, new WeakSet()); // true
is(String, ''); // true
is(String, new String('')); // true
is(Number, 1); // true
is(Number, new Number(1)); // true
is(Boolean, true); // true
is(Boolean, new Boolean(true)); // true

# 大小写转换

。str 待转换的字符串

。type 1-全大写 2-全小写 3-首字母大写


export const turnCase = (str, type) => {
  switch (type) {
    case 1:
      return str.toUpperCase()
    case 2:
      return str.toLowerCase()
    case 3:
      //return str[0].toUpperCase() + str.substr(1).toLowerCase() // substr 已不推荐使用
      return str[0].toUpperCase() + str.substring(1).toLowerCase()
    default:
      return str
  }
}
turnCase('vue', 1) // VUE
turnCase('REACT', 2) // react
turnCase('vue', 3) // Vue

# 字符串中每个单词的首字母大写


const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());

capitalizeEveryWord('hello world!'); // 'Hello World!'

第一个字母转换为小写


const decapitalize = ([first, ...rest]) =>
  first.toLowerCase() + rest.join('')

decapitalize('FooBar'); // 'fooBar'
decapitalize('FooBar'); // 'fooBar'

# 切换变量


[foo, bar] = [bar, foo];

# 随机布尔值


const randomBoolean = () => Math.random() >= 0.5;
randomBoolean();

# 生成随机字符串 1


const randomstr = Math.random().toString(36).substring(2)

生成随机字符串 2



const randomString = (len) => {
  let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789";
  let strLen = chars.length;
  let randomStr = "";
  for (let i = 0; i < len; i++) {
    randomStr += chars.charAt(Math.floor(Math.random() * strLen));
  }
  return randomStr;
};

randomString(10) // pfkMfjEJ6x
randomString(20) // ce6tEx1km4idRNMtym2S

# 反转字符串


const rev = (str) => str.split("").reverse().join("")

# 四舍五入到指定位数


const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d);
round(1.306561215165, 2) //1.31

# 小数点后两位


parseFloat("183.456").toFixed(2);

# 从两个整数中确定随机整数


const random = (min, max) => Math.floor(Math.random() * (max — min + 1) + min);
random(1, 50);

# 从字符串中删除 HTML


const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';

# 字符串截断


const truncateString = (string, length) => string.length < length ? string : `${string.slice(0, length - 3)}...`;
truncateString('Hi, I should be truncated because I am too loooong!', 36)   // 'Hi, I should be truncated because...

# 从中间截断字符串


const truncateStringMiddle = (string, length, start, end) => {
  return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
};

console.log(
  truncateStringMiddle(
    'A long story goes here but then eventually ends!', // string
    25, // 需要的字符串大小
    13, // 从原始字符串第几位开始截取
    17, // 从原始字符串第几位停止截取
  ),
);
// A long story ... eventually ends!

# 将字符串转换为数组


const str = "Hello";
const arr = [...str];
console.log(arr); /* ['H', 'e', 'l', 'l', 'o'] *

# 检查字符串是存在于另一个字符串中


const isAnagram = (str1, str2) => {
  const normalize = str =>
    str
      .toLowerCase()
      .replace(/[^a-z0-9]/gi, '')
      .split('')
      .sort()
      .join('');
  return normalize(str1) === normalize(str2);
};
isAnagram('iceman', 'cinema'); // true

方法 2


const val1 = "atitpatel";
const val2 = "patel";
console.log(string.includes(val2));

方法 3


var str = "atitpatel";
var substr = "patel";
console.log(str.indexOf(substr) !== -1);

# 检查值是否为 null 或 undefined


const isNil = val => val === undefined || val === null;

isNil(null); // true
isNil(undefined); // true

# 值是否为数字


function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

isNumber('1'); // false
isNumber(1); // true

# 以字节为单位返回字符串的长度


const byteSize = str => new Blob([str]).size;
byteSize('😀'); // 4
byteSize('Hello World'); // 11

# 替换所有出现的字符串


str = str.replace(/test/g, '');

还可以用正则


let find = 'ab';
let re = new RegExp(find, '');
let str = find.replace(re, 'cd');
console.log(str);

# 将字符串转换为 URL Slug


const slugify = string => string.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');

slugify('Episode IV: A New Hope');    
// Result:'episode-iv-a-new-hope
知识汇总   |