Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

字数统计管道实现 #56

Open
alanhe421 opened this issue Jun 21, 2018 · 0 comments
Open

字数统计管道实现 #56

alanhe421 opened this issue Jun 21, 2018 · 0 comments
Labels
Pipe 管道

Comments

@alanhe421
Copy link
Owner

alanhe421 commented Jun 21, 2018

我在制作博客平台时候有这样一个需求,就是字数统计,这里记录下实现
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,所以多了提取内容的处理。

@alanhe421 alanhe421 added the Pipe 管道 label Jun 21, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Pipe 管道
Projects
None yet
Development

No branches or pull requests

1 participant