StringUtils.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /** @format */
  2. // ---------String-----------
  3. interface String {
  4. /**
  5. * 对一个字符串中出现的字符串全部替换为另一个字符串
  6. * @param oldString 被替换的字符串
  7. * @param newString 新的字符串
  8. */
  9. replaceAll(oldString: string, newString: string): string
  10. trimLeftAndRight(): string
  11. trimLeft(): string
  12. trimRight(): string
  13. /**
  14. * 计算字符串长度,半角长度为1,全角长度为2
  15. * @return 字符串长度
  16. */
  17. getStrLen(): number
  18. /**
  19. * 判断字符是全角还是半角
  20. * @param char 字符
  21. * @return true:半角 false:全角
  22. */
  23. isDbcCase(char: number): boolean
  24. zeroPrefix(num: number, n: number): string
  25. }
  26. String.prototype.replaceAll = function (oldString: string, newString: string) {
  27. return this.replace(new RegExp(oldString, 'g'), newString)
  28. }
  29. String.prototype.trimLeftAndRight = function () {
  30. return this.replace(/(^\s*)|(\s*$)/g, '')
  31. }
  32. String.prototype.trimLeft = function () {
  33. return this.replace(/(^\s*)/g, '')
  34. }
  35. String.prototype.trimRight = function () {
  36. return this.replace(/(\s*$)/g, '')
  37. }
  38. String.prototype.isDbcCase = function (char: number) {
  39. let ret = false
  40. if (char >= 32 && char <= 127) {
  41. ret = true // 基本拉丁字母(即键盘上可见的,空格、数字、字母、符号)
  42. } else if (char >= 65377 && char <= 65439) {
  43. ret = true // 日文半角片假名和符号
  44. }
  45. return ret
  46. }
  47. String.prototype.getStrLen = function () {
  48. let len = 0
  49. for (let i = 0; i < this.length; i++) {
  50. len += this.isDbcCase(this.charCodeAt(i)) ? 1 : 2
  51. }
  52. return len
  53. }
  54. String.prototype.zeroPrefix = function (num: number, n: number): string {
  55. return (Array(n).join('0') + num).slice(-n)
  56. }