Skip to content

字数统计管道实现 #56

@alanhe421

Description

@alanhe421

我在制作博客平台时候有这样一个需求,就是字数统计,这里记录下实现
wordcount.pipe.ts

import {Pipe, PipeTransform} from '@angular/core';
import * as wordcount from "wordcount";

/**
 * 这里的value是html源码所以进行下内容转化
 * 计算字符数需要考虑中英文和英文单词问题
 */
@Pipe({
  name: 'wordcount'
})
export class WordcountPipe implements PipeTransform {

  transform(value: string, args?: any): number {
    const divObj = document.createElement("div");
    divObj.innerHTML = value;
    value = divObj.textContent;
    return counter(value);
  }
}

/**
 * 字数统计,考虑中英文
 * @param {string} content
 * @returns {number}
 */
function counter(content: string) {
  const cn = content.match(/[\u4E00-\u9FA5]/g) || [];
  const en = content.replace(/[\u4E00-\u9FA5]/g, '');
  return cn.length + wordcount(en);
}

注意这里管道的输入参数是html,所以多了提取内容的处理。

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions