Skip to content
On this page

字符串 api 使用以及源码实现

TIP

不要说 api 都不知道怎么用的,告诉我说数据处理复杂。本篇总结字符串常用的 api 以及实现原理, 字符串处理必会 api。

1、concat 字符串拼接

TIP

字符串拼接,不更改原始数据,返回一个新的字符串。多个一块拼接使用逗号隔开

js
'1232'.concat('1', '2'); // '123212'

// 源码实现
const _concat = (source, ...args) => {
  let results = source;
  args.forEach((item) => (results += item));
  return results;
};

_concat('123', '1', '2'); // '12312'

2、includes 是否包含

TIP

字符串是否包含,包含返回true,不包含返回false

js
'1232'.includes('1'); // true;

const _includes = (source: string, target: string) => {
  let results = false;
  const len = target.length;
  for (let index = 0; index < source.length; index++) {
    const currentValue = source.substr(index, len);
    if (currentValue === target) {
      return true;
    }
  }

  return results;
};

_includes('123', '1'); // true

3、indexOf 返回对应的索引

TIP

字符串从前查找索引,有这个字符返回对应的索引,没有返回-1;

js
'123'.indexOf('2'); // 1

export const _indexOf = (source: string, target: string) => {
  let results = -1;
  const len = target.length;
  for (let index = 0; index < source.length; index++) {
    const currentValue = source.substr(index, len);
    if (currentValue === target) {
      return index;
    }
  }

  return results;
};

_indexOf('123', '2'); // 1

4、lastIndexOf 返回对应的索引

TIP

字符串向后查找索引,有这个字符返回对应的索引,没有返回-1;

js
'1231'.lastIndexOf('1'); // 3

export const _lastIndexOf = (source: string, target: string) => {
  let results = -1;
  const len = target.length;
  for (let index = source.length; index > 0; index--) {
    const startIndex = index - len;
    if (startIndex < 0) {
      break;
    }
    const currentValue = source.substr(startIndex, len);
    if (currentValue === target) {
      return startIndex;
    }
  }

  return results;
};

_lastIndexOf('122221', '1'); // 5

5、endsWith 结束检验是否包含字符串

TIP

字符串结束检验是否包含字符串, 尾部包含返回 true, 尾部不包含返回 false

js
'123'.endsWith('3'); // true

export const _endsWith = (source: string, target: string) => {
  const len = target.length;
  const substrValue = source.substr(source.length - len, len);

  return substrValue === target;
};

_endsWith('123456', '56'); // true

6、startsWith 结束检验是否包含字符串

TIP

字符串开始检验是否包含字符串, 开始包含返回 true, 开始不包含返回 false

js
'123'.startsWith('1'); // true;

export const _startsWith = (source: string, target: string) => {
  const len = target.length;
  const substrValue = source.substr(0, len);
  return substrValue === target;
};

_startsWith('123', '1'); // true

7、padStart 前面填补

TIP

字符串的长度不够用参数往前填补

js
'1'.padStart(2, 0); // '01'

export const _padStart = (source: string, count: number, target: any) => {
  const strTargetValue = `${target}`;
  const len = strTargetValue.length;
  const sum = Math.ceil(count / len);
  const rendyValue = new Array(sum)
    .fill('0')
    .map(() => strTargetValue)
    .join('');

  const startValue = rendyValue.substr(0, count - source.length);
  return startValue.concat(source);
};

_padStart('1', 5, '12'); // '12121'

8、padEnd 后面填补

TIP

字符串的长度不够用参数后面填补

js
'12'.padEnd(5, 0); // '12000'

export const _padEnd = (source: string, count: number, target: any) => {
  const strTargetValue = `${target}`;
  const len = strTargetValue.length;
  const sum = Math.ceil(count / len);
  const rendyValue = new Array(sum)
    .fill('0')
    .map(() => strTargetValue)
    .join('');

  const endValue = rendyValue.substr(0, count - source.length);
  return source.concat(endValue);
};

_padEnd('12', 5, 0); // '12000'

9、substring 字符串截取

TIP

字符串截取,第一个是开始索引,第二个结束索引(不传默认结尾),不改变原数据。

js
'123'.substring(1, 3); // '23';

export const _substring = (
  source: string,
  startIndex: number,
  endIndex: number = source.length
) => {
  let results = '';
  for (let index = 0; index < source.length; index++) {
    if (index >= startIndex && index < endIndex) {
      results += source[index];
    }
  }

  return results;
};

_substring('123', 1, 2); // '2'

9、substr 字符串截取

TIP

字符串截取,第一个是开始索引,第二个数量(不传默认结尾),不改变原数据。

js
'12345'.substr(2, 2); // '34'

export const _substr = (
  source: string,
  startIndex: number,
  count: number = source.length
) => {
  let results = '';
  let initCount = 0;
  for (let index = 0; index < source.length; index++) {
    if (index >= startIndex && initCount < count) {
      results += source[index];
      initCount++;
    }
  }

  return results;
};

_substr('12345', 2, 2); // '34'

10、toLocaleLowerCase / toLocaleUpperCase 字符串字母转小/大写

TIP

字符串字母转大小写

js
'abc'.toLocaleUpperCase(); // 'ABC';
'ABC'.toLocaleLowerCase(); // 'abc';

const lowerList = [
  'a',
  'b',
  'c',
  'd',
  'e',
  'f',
  'g',
  'h',
  'i',
  'j',
  'k',
  'm',
  'n',
  'o',
  'p',
  'q',
  'r',
  's',
  't',
  'u',
  'v',
  'w',
  'x',
  'y',
  'z',
];
const upperList = [
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z',
];
// 小写
export const _toLocaleLowerCase = (source: string) => {
  let results = '';
  for (let index = 0; index < source.length; index++) {
    const element = source[index];
    const findIndex = upperList.findIndex((item) => item === element);
    if (findIndex === -1) {
      results += element;
    } else {
      results += lowerList[findIndex];
    }
  }
  return results;
};

// 大写
export const _toLocaleUpperCase = (source: string) => {
  let results = '';
  for (let index = 0; index < source.length; index++) {
    const element = source[index];
    const findIndex = lowerList.findIndex((item) => item === element);
    if (findIndex === -1) {
      results += element;
    } else {
      results += upperList[findIndex];
    }
  }
  return results;
};

_toLocaleLowerCase('ABC'); // 'abc'
_toLocaleUpperCase('abc'); // 'ABC'

11、trim / trimStart / trimEnd 字符串去除前后空格

TIP

字符串去除前后空格

js
' abc '.trim(); // 'abc';
' abc '.trimStart(); // 'abc ';
' abc '.trimEnd(); // ' abc';

export const _trmeStart = (source: string) => {
  let results = '';
  let startFlag = false;
  for (let index = 0; index < source.length; index++) {
    const element = source[index];
    if (element !== ' ' && !startFlag) {
      startFlag = true;
    }

    if (startFlag) {
      results += element;
    }
  }

  return results;
};

export const _trmeEnd = (source: string) => {
  let results = '';
  let startFlag = false;
  for (let index = source.length - 1; index >= 0; index--) {
    const element = source[index];
    if (element !== ' ' && !startFlag) {
      startFlag = true;
    }

    if (startFlag) {
      results = element + results;
    }
  }

  return results;
};

export const _trim = (source: string) => {
  return _trmeStart(_trmeEnd(source));
};

_trim(' abc '); // 'abc';
_trimStart(' abc '); // 'abc ';
_trimEnd(' abc '); // ' abc';

Released under the MIT License.